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

How can I take multiple occurrences of 5 out of a list?

None the less,这是应该取出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

有什么帮助吗?

你说你想取出 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]
>>> 

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]

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.

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

您执行此操作的最简单方法是 return 一个没有您要删除的元素的新列表,并将其分配回 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]

另一种方法是使用内置方法 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]