Remove all occurrences of a value from a list?

后端 未结 23 1865
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:45

In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list?

This is w

相关标签:
23条回答
  • 2020-11-21 23:59
    hello =  ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
    #chech every item for a match
    for item in range(len(hello)-1):
         if hello[item] == ' ': 
    #if there is a match, rebuild the list with the list before the item + the list after the item
             hello = hello[:item] + hello [item + 1:]
    print hello
    

    ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

    0 讨论(0)
  • 2020-11-22 00:00

    you can do this

    while 2 in x:   
        x.remove(2)
    
    0 讨论(0)
  • 2020-11-22 00:00
    for i in range(a.count(' ')):
        a.remove(' ')
    

    Much simpler I believe.

    0 讨论(0)
  • 2020-11-22 00:03
    p=[2,3,4,4,4]
    p.clear()
    print(p)
    []
    

    Only with Python 3

    0 讨论(0)
  • 2020-11-22 00:05

    At the cost of readability, I think this version is slightly faster as it doesn't force the while to reexamine the list, thus doing exactly the same work remove has to do anyway:

    x = [1, 2, 3, 4, 2, 2, 3]
    def remove_values_from_list(the_list, val):
        for i in range(the_list.count(val)):
            the_list.remove(val)
    
    remove_values_from_list(x, 2)
    
    print(x)
    
    0 讨论(0)
  • 2020-11-22 00:06

    Functional approach:

    Python 3.x

    >>> x = [1,2,3,2,2,2,3,4]
    >>> list(filter((2).__ne__, x))
    [1, 3, 3, 4]
    

    or

    >>> x = [1,2,3,2,2,2,3,4]
    >>> list(filter(lambda a: a != 2, x))
    [1, 3, 3, 4]
    

    Python 2.x

    >>> x = [1,2,3,2,2,2,3,4]
    >>> filter(lambda a: a != 2, x)
    [1, 3, 3, 4]
    
    0 讨论(0)
提交回复
热议问题