我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
上面给出了错误:
ValueError: list.index(x): x not in list
所以我必须这样做:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)
难道没有更简单的方法吗?
我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
上面给出了错误:
ValueError: list.index(x): x not in list
所以我必须这样做:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)
难道没有更简单的方法吗?
当前回答
这个例子是快速的,并且会从列表中删除一个值的所有实例:
a = [1,2,3,1,2,3,4]
while True:
try:
a.remove(3)
except:
break
print a
>>> [1, 2, 1, 2, 4]
其他回答
list1=[1,2,3,3,4,5,6,1,3,4,5]
n=int(input('enter number'))
while n in list1:
list1.remove(n)
print(list1)
要删除一个元素的第一次出现,使用list.remove:
>>> xs = ['a', 'b', 'c', 'd']
>>> xs.remove('b')
>>> print(xs)
['a', 'c', 'd']
要移除所有出现的元素,使用列表推导式:
>>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b']
>>> xs = [x for x in xs if x != 'b']
>>> print(xs)
['a', 'c', 'd']
一些最简单的基准测试方法:
import random
from copy import copy
sample = random.sample(range(100000), 10000)
remove = random.sample(range(100000), 1000)
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
for i in reversed(sample1):
if i in remove1:
sample1.remove(i)
# 271 ms ± 16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
filtered = list(filter(lambda x: x not in remove1, sample1))
# 280 ms ± 18.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
filtered = [ele for ele in sample1 if ele not in remove1]
# 293 ms ± 72.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
for val in remove1:
if val in sample1:
sample1.remove(val)
# 558 ms ± 40.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
for val in remove1:
try:
sample1.remove(val)
except:
pass
# 609 ms ± 11.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence
考虑:
a = [1,2,2,3,4,5]
要去除所有的事件,可以使用python中的filter函数。 例如,它看起来是这样的:
a = list(filter(lambda x: x!= 2, a))
因此,它将保留a != 2的所有元素。
只要拿出其中一项使用
a.remove(2)
这个例子是快速的,并且会从列表中删除一个值的所有实例:
a = [1,2,3,1,2,3,4]
while True:
try:
a.remove(3)
except:
break
print a
>>> [1, 2, 1, 2, 4]