我想从列表中删除一个值,如果它存在于列表中(可能不存在)。
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)上面的情况(其中它不存在)显示了以下错误:
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b = a.index(6)
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)但是,没有更简单的方法来做到这一点吗?
发布于 2010-05-08 22:57:39
下面是如何就地完成它(不需要列表理解):
def remove_all(seq, value):
pos = 0
for item in seq:
if item != value:
seq[pos] = item
pos += 1
del seq[pos:]https://stackoverflow.com/questions/2793324
复制相似问题