代码之家  ›  专栏  ›  技术社区  ›  juangalicia

python中的append方法是怎么回事

  •  -2
  • juangalicia  · 技术社区  · 2 年前
    def max_zero_sequence(arr): 
        # your code here
        sequence = list()
        answers = list()
        start = 0
    
        while start < len(arr):
        
            for i in arr[start:]:
            
                sequence.append(i)
                if sum(sequence) == 0:
                    answers.append(sequence)
    
            sequence = []
            start += 1 
        
        print(answers)
    

    试图得到最长的整数序列,它们的和等于零。在这种情况下,如果arr等于[1,2,-3,7,8,-16],则答案必须是[1,2、-3]。 那么,有人能解释为什么python返回[[1,2,3,7,8,16]吗???? 应该附加到答案列表中的顺序是[1,2,-3]。

    3 回复  |  直到 2 年前
        1
  •  2
  •   Nonlinear    2 年前

    sequence 将其附加到后仍会更改 answers .将第13行从 answers.append(sequence) answers.append(sequence.copy()) 解决您的问题。

        2
  •  2
  •   binaryescape    2 年前

    下面的代码应该可以满足您的要求。你必须将序列列表的副本存储到答案中,否则答案只包含一个引用,即你一直附加到的原始序列列表。

    def max_zero_sequence(arr):
        seq = list()
        ans = list()
        start = 0
        while start < len(arr):
            for i in arr[start:]:
                seq.append(i)
                if sum(seq) == 0 and len(seq) > len(ans):
                    ans = seq.copy()
            seq = list()
            start += 1
        print(ans)
    
        3
  •  2
  •   SIGHUP    2 年前

    一旦你确定了一个和为零的序列,你就应该将其长度与之前观察到的任何符合标准的序列进行比较。如果新的序列比上一个序列长,请注意。

    类似于以下内容:

    def max_zero_sequence(lst):
        result = []
    
        for s in range(len(lst)):
            for e in range(len(lst), s, -1):
                seq = lst[s:e]
                if sum(seq) == 0 and len(seq) > len(result):
                    result = seq
    
        return result
    
    print(max_zero_sequence([1, 2, -3, 7, 8, -16]))
    print(max_zero_sequence([1, 2, -3, 7, 1, -1, 0, 0, 0, 2, -1, -1, 8, -16]))
    

    输出:

    [1, 2, -3]
    [1, -1, 0, 0, 0, 2, -1, -1]
    
    推荐文章