在Python中remove()将删除列表中第一个出现的值。
如何从列表中删除一个值的所有出现?
这就是我的想法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
在Python中remove()将删除列表中第一个出现的值。
如何从列表中删除一个值的所有出现?
这就是我的想法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
当前回答
您可以将列表转换为numpy。数组,然后使用np.delete并传递该元素及其所有出现的元素的索引。
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7]
element_to_remove = 3
my_array = np.array(my_list)
indices = np.where(my_array == element_to_remove)
my_array = np.delete(my_array, indices)
my_list = my_array.tolist()
print(my_list)
#output
[1, 2, 4, 5, 6, 7, 4, 5, 6, 7]
其他回答
以更抽象的方式重复第一篇文章的解决方案:
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> while 2 in x: x.remove(2)
>>> x
[1, 3, 4, 3]
删除所有重复的出现,并在列表中保留一个:
test = [1, 1, 2, 3]
newlist = list(set(test))
print newlist
[1, 2, 3]
下面是我在Project Euler中使用的函数:
def removeOccurrences(e):
return list(set(e))
很多答案都很好。如果你是python初学者,这里有一个简单的方法,以防你肯定想使用remove()方法。
rawlist = [8, 1, 8, 5, 8, 2, 8, 9, 8, 4]
ele_remove = 8
for el in rawlist:
if el == ele_remove:
rawlist.remove(ele_remove)
对于太大的列表,它可能会慢一些。
hello = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
if hello[item] == ' ':
#if there is a match, rebuild the list with the list before the item + the list after the item
hello = hello[:item] + hello [item + 1:]
print hello
[' h ',‘e’,‘l’,‘l’,‘o’,‘w’,‘o’,‘r’,‘l’,' d ')
更好的解决方案与列表理解
x = [ i for i in x if i!=2 ]