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

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 = [1,2,2,3,4,5]

要去除所有的事件,可以使用python中的filter函数。 例如,它看起来是这样的:

a = list(filter(lambda x: x!= 2, a))

因此,它将保留a != 2的所有元素。

只要拿出其中一项使用

a.remove(2)

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

这将从数组sys中删除"-v"的所有实例。Argv,如果没有找到实例,则不报错:

while "-v" in sys.argv:
    sys.argv.remove('-v')

你可以在一个名为speechToText.py的文件中看到代码的运行:

$ python speechToText.py -v
['speechToText.py']

$ python speechToText.py -x
['speechToText.py', '-x']

$ python speechToText.py -v -v
['speechToText.py']

$ python speechToText.py -v -v -x
['speechToText.py', '-x']

如果你的元素是不同的,那么一个简单的集合差异就可以了。

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]