有没有一种简单的方法可以按值删除列表元素?

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

答案

>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']
>>> 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]
if c in a:
    a.remove(c)
try:
    a.remove(c)
except ValueError:
    pass
a=[1,2,3,4]
if 6 in a:
    a.remove(6)
try:
    a.remove(6)
except:
    pass
a = [1,2,2,3,4,5]
a = list(filter(lambda x: x!= 2, a))
a.remove(2)
def remove_all(seq, value):
    pos = 0
    for item in seq:
        if item != value:
           seq[pos] = item
           pos += 1
    del seq[pos:]
a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
    a.remove(1)
my_set=set([3,4,2])
my_set.discard(1)
my_set.add(3)
from contextlib import suppress
with suppress(ValueError):
    a.remove('b')
>>> 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
a = [1,2,3,1,2,3,4]
while True:
    try:
        a.remove(3)
    except:
        break
print a
>>> [1, 2, 1, 2, 4]