我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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)
难道没有更简单的方法吗?
当前回答
这就是我的答案,用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()
其他回答
以下是如何做到这一点(不需要理解列表):
def remove_all(seq, value):
pos = 0
for item in seq:
if item != value:
seq[pos] = item
pos += 1
del seq[pos:]
通常,如果你告诉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)
当nums是列表,c是要删除的值时:
要删除列表中第一个出现的c,只需执行以下操作:
if c in nums:
nums.remove(c)
要从列表中删除所有出现的c,请执行以下操作:
while c in nums:
nums.remove(c)
添加异常处理将是最佳实践,但我主要想演示如何从列表中删除所有出现的元素。
在列表中查找一个值,然后删除该索引(如果它存在的话),使用list的remove方法更容易完成:
>>> a = [1, 2, 3, 4]
>>> try:
... a.remove(6)
... except ValueError:
... pass
...
>>> print a
[1, 2, 3, 4]
>>> try:
... a.remove(3)
... except ValueError:
... pass
...
>>> print a
[1, 2, 4]
如果你经常这样做,你可以把它包在一个函数中:
def remove_if_exists(L, value):
try:
L.remove(value)
except ValueError:
pass