我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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)
难道没有更简单的方法吗?
当前回答
arr = [1, 1, 3, 4, 5, 2, 4, 3]
# to remove first occurence of that element, suppose 3 in this example
arr.remove(3)
# to remove all occurences of that element, again suppose 3
# use something called list comprehension
new_arr = [element for element in arr if element!=3]
# if you want to delete a position use "pop" function, suppose
# position 4
# the pop function also returns a value
removed_element = arr.pop(4)
# u can also use "del" to delete a position
del arr[4]
其他回答
通过索引除希望删除的元素之外的所有内容来覆盖列表
>>> s = [5,4,3,2,1]
>>> s[0:2] + s[3:]
[5, 4, 2, 1]
更普遍的是,
>>> s = [5,4,3,2,1]
>>> i = s.index(3)
>>> s[:i] + s[i+1:]
[5, 4, 2, 1]
另一种可能是使用set而不是list,如果set适用于您的应用程序。
IE中如果你的数据不是有序的,并且没有副本,那么
my_set=set([3,4,2])
my_set.discard(1)
是没有错误的。
通常,列表只是一个方便的容器,用于存放实际上是无序的项目。有些问题询问如何从列表中删除一个元素的所有出现。如果你一开始就不想被骗,一套也很方便。
my_set.add(3)
不改变上面的my_set。
通常,如果你告诉Python做一些它不能做的事情,Python会抛出一个异常,所以你必须这样做:
if c in a:
a.remove(c)
or:
try:
a.remove(c)
except ValueError:
pass
异常不一定是坏事,只要它是您所期望的并正确处理的。
正如许多其他答案所述,list.remove()将工作,但如果项不在列表中则抛出ValueError。在python 3.4+中,有一个有趣的方法来处理这个问题,使用suppress contextmanager:
from contextlib import suppress
with suppress(ValueError):
a.remove('b')
要删除一个元素的第一次出现,使用list.remove:
>>> xs = ['a', 'b', 'c', 'd']
>>> xs.remove('b')
>>> print(xs)
['a', 'c', 'd']
要移除所有出现的元素,使用列表推导式:
>>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b']
>>> xs = [x for x in xs if x != 'b']
>>> print(xs)
['a', 'c', 'd']