如何从列表中多次出现5个?

时间:2015-07-12 14:53:53

标签: python list loops operators

尽管如此,这是应该取出5的所有实例的函数的代码,但是我收到错误:

i = [ 6 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 5 ]

def removeFive ( i ) :
    x = 0
    amount = len ( i )
    for x in range ( amount - 1 ) :
        if i [ x ] == 5 :
            i . remove ( [ x ] )
        else:
            pass
        x = x + 1
    print ( i )
    return None

removeFive ( i ) 

错误消息:

i . remove ( [ x ] )
ValueError: list.remove(x): x not in list

任何帮助?

4 个答案:

答案 0 :(得分:2)

你说你想取出5的所有实例这是一种方法:

>>> i = [ 6 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 5 ]
>>> x = [e for e in i if e != 5]
>>> x
[6, 2, 3, 4, 6, 7, 8, 9, 10]
>>> 

答案 1 :(得分:1)

list.remove()函数实际上接受要删除的元素,在本例中为5,而不是索引(尤其不是作为列表的索引)。这就是你得到错误的原因。此行为的示例 -

>>> l = [5,4,3,2,1]
>>> l.remove(1)
>>> l
[5, 4, 3, 2]   #note that element 3 got removed not the index 3.

此外,您不应该在迭代时从列表中删除元素,因为第一次更改列表时,元素的索引也会更改(由于删除),因此您错过了检查某些元素。

执行此操作的最简单方法是返回一个没有要删除的元素的新列表,并将其分配回i,示例 -

def removeFive ( i ) :
    return [x for x in i if x != 5]
i = removeFive(i)
i
>>> [6, 2, 3, 4, 6, 7, 8, 9, 10]

你甚至不需要一个功能 -

i = [x for x in i if x != 5]
i
>>> [6, 2, 3, 4, 6, 7, 8, 9, 10]

答案 2 :(得分:1)

另一种方法是使用内置方法filter,这样:

>>> i = [ 6 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 5 ]
>>> filter(lambda x: x!=5, i)
[6, 2, 3, 4, 6, 7, 8, 9, 10]

答案 3 :(得分:0)

list.remove方法接受的值不是它的索引,所以首先需要传递一个值来删除,同样你已经在列表中传递了索引,似乎你要传递i[x]

但是作为一种更加pythonic的方式,你可以使用列表理解来删除5:

>>> i = [ 6 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 5 ]
>>> [t for t in i if t!=5]
[6, 2, 3, 4, 6, 7, 8, 9, 10]
相关问题