我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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,4]
if 6 in a:
a.remove(6)
但以上需要在list a中搜索2次6,所以尝试except会更快
try:
a.remove(6)
except:
pass
其他回答
正如许多其他答案所述,list.remove()将工作,但如果项不在列表中则抛出ValueError。在python 3.4+中,有一个有趣的方法来处理这个问题,使用suppress contextmanager:
from contextlib import suppress
with suppress(ValueError):
a.remove('b')
这就是我的答案,用while和for就可以了
def remove_all(data, value):
i = j = 0
while j < len(data):
if data[j] == value:
j += 1
continue
data[i] = data[j]
i += 1
j += 1
for x in range(j - i):
data.pop()
你可以这样做
a=[1,2,3,4]
if 6 in a:
a.remove(6)
但以上需要在list a中搜索2次6,所以尝试except会更快
try:
a.remove(6)
except:
pass
通常,如果你告诉Python做一些它不能做的事情,Python会抛出一个异常,所以你必须这样做:
if c in a:
a.remove(c)
or:
try:
a.remove(c)
except ValueError:
pass
异常不一定是坏事,只要它是您所期望的并正确处理的。
这是一个效率较低的解决方案,但它仍然有效:
A =[] //这是你的列表
B //需要删除的元素
counter = a.count(b)
while counter > 0:
if b in a:
a.remove(b)
counter -= 1
print(a)