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

后端 未结 21 1555
我寻月下人不归
我寻月下人不归 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:00

    This example is fast and will delete all instances of a value from the list:

    a = [1,2,3,1,2,3,4]
    while True:
        try:
            a.remove(3)
        except:
            break
    print a
    >>> [1, 2, 1, 2, 4]
    
    0 讨论(0)
  • 2020-11-22 13:00

    Overwrite the list by indexing everything except the elements you wish to remove

    >>> s = [5,4,3,2,1]
    >>> s[0:2] + s[3:]
    [5, 4, 2, 1]
    

    More generally,

    >>> s = [5,4,3,2,1]
    >>> i = s.index(3)
    >>> s[:i] + s[i+1:]
    [5, 4, 2, 1]
    
    0 讨论(0)
  • 2020-11-22 13:01

    If your elements are distinct, then a simple set difference will do.

    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]
    
    0 讨论(0)
  • 2020-11-22 13:05

    This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:

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

    You can see the code in action, in a file called 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']
    
    0 讨论(0)
  • 2020-11-22 13:09
    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]
    
    0 讨论(0)
  • 2020-11-22 13:12

    We can also use .pop:

    >>> lst = [23,34,54,45]
    >>> remove_element = 23
    >>> if remove_element in lst:
    ...     lst.pop(lst.index(remove_element))
    ... 
    23
    >>> lst
    [34, 54, 45]
    >>> 
    
    0 讨论(0)
提交回复
热议问题