Is there a simple way to delete a list element by value?

后端 未结 21 1732
我寻月下人不归
我寻月下人不归 2020-11-22 12:20

I want to remove a value from a list if it exists in the list (which it may not).

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

The abov

21条回答
  •  孤独总比滥情好
    2020-11-22 13:19

    Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:

    >>> 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]
    

    If you do this often, you can wrap it up in a function:

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

提交回复
热议问题