有没有一种简单的方法可以按值删除列表元素?
问题描述:
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)
但是有没有更简单的方法来做到这一点?
But is there not a simpler way to do this?
答
要删除元素在列表中的首次出现,只需使用list.remove
:
To remove an element's first occurrence in a list, simply use list.remove
:
>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print(a)
['a', 'c', 'd']
请注意,它不会删除所有出现的元素.为此,请使用列表理解.
Mind that it does not remove all occurrences of your element. Use a list comprehension for that.
>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]