我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。

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]

其他回答

这是一个效率较低的解决方案,但它仍然有效:

A =[] //这是你的列表

B //需要删除的元素

counter = a.count(b)

while counter > 0:
    if b in a:
       a.remove(b)
       counter -= 1

print(a)

另一种可能是使用set而不是list,如果set适用于您的应用程序。

IE中如果你的数据不是有序的,并且没有副本,那么

my_set=set([3,4,2])
my_set.discard(1)

是没有错误的。

通常,列表只是一个方便的容器,用于存放实际上是无序的项目。有些问题询问如何从列表中删除一个元素的所有出现。如果你一开始就不想被骗,一套也很方便。

my_set.add(3)

不改变上面的my_set。

当nums是列表,c是要删除的值时:

要删除列表中第一个出现的c,只需执行以下操作:

if c in nums:
    nums.remove(c)

要从列表中删除所有出现的c,请执行以下操作:

while c in nums:
    nums.remove(c)

添加异常处理将是最佳实践,但我主要想演示如何从列表中删除所有出现的元素。

要删除一个元素的第一次出现,使用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']

这里的许多答案都涉及到创建一个新列表。这涉及到将所有数据从旧列表复制到新列表(删除的项除外)。如果你的清单很长,你可能负担不起(或者你不应该想要)。

在这些情况下,就地更改列表要快得多。如果你必须从列表中删除一个以上的元素,这可能会很棘手。假设您循环遍历列表,并删除了一个项,那么列表将更改,标准for循环将不考虑这一点。循环的结果可能不是您所期望的。

例子:

a = [0, 1, 2, 3, 4, 5]
for i in a:
    a.remove(i)  # Remove all items
print(a)

Out: [1, 3, 5]

一个简单的解决方案是以相反的顺序遍历列表。在这种情况下,你会得到:

a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
    a.remove(i)  # Remove all items
print(a)

Out: []

然后,如果你只需要删除一些特定值的元素,你可以简单地在循环中放入一个if语句,结果是:

a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
    if i == 2 or i == 3:  # Remove all items having value 2 or 3.
        a.remove(i)
print(a)

Out: [0, 1, 4, 5]