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

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)

难道没有更简单的方法吗?


当前回答

这就是我的答案,用while和for就可以了

def remove_all(data, value):
    i = j = 0
    while j < len(data):
        if data[j] == value:
            j += 1
            continue
        data[i] = data[j]
        i += 1
        j += 1
    for x in range(j - i):
        data.pop()

其他回答

这将从数组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']

使用一个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

异常不一定是坏事,只要它是您所期望的并正确处理的。

在列表中查找一个值,然后删除该索引(如果它存在的话),使用list的remove方法更容易完成:

>>> a = [1, 2, 3, 4]
>>> try:
...   a.remove(6)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 3, 4]
>>> try:
...   a.remove(3)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 4]

如果你经常这样做,你可以把它包在一个函数中:

def remove_if_exists(L, value):
  try:
    L.remove(value)
  except ValueError:
    pass

一些最简单的基准测试方法:

import random
from copy import copy
sample = random.sample(range(100000), 10000)
remove = random.sample(range(100000), 1000)

%%timeit
sample1 = copy(sample)
remove1 = copy(remove)

for i in reversed(sample1):
    if i in remove1:
        sample1.remove(i)
# 271 ms ± 16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances

%%timeit
sample1 = copy(sample)
remove1 = copy(remove)

filtered = list(filter(lambda x: x not in remove1, sample1))
# 280 ms ± 18.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances

%%timeit
sample1 = copy(sample)
remove1 = copy(remove) 

filtered = [ele for ele in sample1 if ele not in remove1]
# 293 ms ± 72.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances

%%timeit
sample1 = copy(sample)
remove1 = copy(remove) 

for val in remove1:
    if val in sample1:
        sample1.remove(val)
# 558 ms ± 40.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence

%%timeit
sample1 = copy(sample)
remove1 = copy(remove) 

for val in remove1:
    try:
        sample1.remove(val)
    except:
        pass
# 609 ms ± 11.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence