Python:使用del或list.remove进行列表操作

时间:2015-11-03 19:07:49

标签: python list del

我正在尝试编写一个函数。此函数将数字列表作为输入,查找此列表中连续数字的最大序列,并返回仅包含原始列表中最大数字序列的列表。

示例:

In [2]: largestSeq([1,2,3,4,1,2,3])
Out[2]: [1, 2, 3, 4]

只要输入列表中包含0个或多个元素,它就可以正常工作。 我在我的代码中包含了print语句,以查看错误的位置。

以下是调用largestSeq([1])largestSeq([1,2])的代码和结果:

代码:

def findSeq(seq):                    #this finds a sequence of consecutive numbers 
        i = 0                        #in a list and returns it
        if len(seq) <= 1:            #it stops when the next number in the list 
            return seq                #is smaller than the former
        s =[seq[0]]
        while seq[i] < seq[i+1]:
            i += 1
            s.append(seq[i])
            if i == len(seq)-1:
                break
        return s
def largestSeq(seq,a=[]):
    b = findSeq(seq)                 #find the first consecutive sequence
    if len(seq) == 0:
        return a
    print 'Length of b is ' + str(len(b))
    if len(b) > len(a):            #check if found sequence is bigger than 
        print 'seq is now ' + str(seq)#the last found sequence
        print 'b is now ' + str(b)
        i = len(b)
        print 'now deleting elements of seq'
        for d in range (i):
            seq.remove(seq[0])    #remove found sequence from the original 
        #del seq[0:i]            #list
        print 'seq is now ' + str(seq)
        print 'b is now ' + str(b)
        return largestSeq(seq,b) #start over
    else:
        del seq[0:len(b)]
        return largestSeq(seq,a)

现在来电:

In [14]: largestSeq([1])
Length of b is 1
seq is now [1]
b is now [1]
now deleting elements of seq
seq is now []
b is now []
Out[14]: []
largestSeq([1,2])
Length of b is 2
seq is now [1, 2]
b is now [1, 2]
now deleting elements of seq
seq is now []
b is now [1, 2]
Out[15]: [1, 2]

请注意,在第一次通话中,b中的元素在删除seq元素后也会被删除,但我没有改变它! 在使用[1,2] b的第二次通话中,表现得像我想要的那样,而seq则会被删除。

我尝试使用list.removedel操作列表(注释掉并产生相同的错误)。

那里发生了什么?我不明白。 我希望b在第一次通话中保持不变,就像在第二次通话中一样。

这是一个非常具体的问题。我会很感激任何建议!

1 个答案:

答案 0 :(得分:1)

在第一种情况下,您将返回相同的列表,您必须返回列表的副本。

尝试:

def findSeq(seq):                    #this finds a sequence of consecutive numbers 
        i = 0                        #in a list and returns it
        if len(seq) <= 1:            #it stops when the next number in the list 
            return list(seq)                #is smaller than the former
        s =[seq[0]]
        while seq[i] < seq[i+1]:
            i += 1
            s.append(seq[i])
            if i == len(seq)-1:
                break
        return s