我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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)
难道没有更简单的方法吗?
当前回答
使用一个for循环和一个条件:
def cleaner(seq, value):
temp = []
for number in seq:
if number != value:
temp.append(number)
return temp
如果你想删除一些,但不是全部:
def cleaner(seq, value, occ):
temp = []
for number in seq:
if number == value and occ:
occ -= 1
continue
else:
temp.append(number)
return temp
其他回答
通常,如果你告诉Python做一些它不能做的事情,Python会抛出一个异常,所以你必须这样做:
if c in a:
a.remove(c)
or:
try:
a.remove(c)
except ValueError:
pass
异常不一定是坏事,只要它是您所期望的并正确处理的。
如果你知道要删除什么值,这里有一个简单的方法(就像我能想到的一样简单):
a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
a.remove(1)
你会得到 [0,0,2,3,4]
使用一个for循环和一个条件:
def cleaner(seq, value):
temp = []
for number in seq:
if number != value:
temp.append(number)
return temp
如果你想删除一些,但不是全部:
def cleaner(seq, value, occ):
temp = []
for number in seq:
if number == value and occ:
occ -= 1
continue
else:
temp.append(number)
return temp
我们也可以使用.pop:
>>> lst = [23,34,54,45]
>>> remove_element = 23
>>> if remove_element in lst:
... lst.pop(lst.index(remove_element))
...
23
>>> lst
[34, 54, 45]
>>>
这个例子是快速的,并且会从列表中删除一个值的所有实例:
a = [1,2,3,1,2,3,4]
while True:
try:
a.remove(3)
except:
break
print a
>>> [1, 2, 1, 2, 4]