Remove all occurrences of a value from a list?

后端 未结 23 1863
佛祖请我去吃肉
佛祖请我去吃肉 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:51

    Repeating the solution of the first post in a more abstract way:

    >>> x = [1, 2, 3, 4, 2, 2, 3]
    >>> while 2 in x: x.remove(2)
    >>> x
    [1, 3, 4, 3]
    
    0 讨论(0)
  • 2020-11-21 23:51

    To remove all duplicate occurrences and leave one in the list:

    test = [1, 1, 2, 3]
    
    newlist = list(set(test))
    
    print newlist
    
    [1, 2, 3]
    

    Here is the function I've used for Project Euler:

    def removeOccurrences(e):
      return list(set(e))
    
    0 讨论(0)
  • 2020-11-21 23:52

    I just did this for a list. I am just a beginner. A slightly more advanced programmer can surely write a function like this.

    for i in range(len(spam)):
        spam.remove('cat')
        if 'cat' not in spam:
             print('All instances of ' + 'cat ' + 'have been removed')
             break
    
    0 讨论(0)
  • 2020-11-21 23:53

    Let

    >>> x = [1, 2, 3, 4, 2, 2, 3]
    

    The simplest and efficient solution as already posted before is

    >>> x[:] = [v for v in x if v != 2]
    >>> x
    [1, 3, 4, 3]
    

    Another possibility which should use less memory but be slower is

    >>> for i in range(len(x) - 1, -1, -1):
            if x[i] == 2:
                x.pop(i)  # takes time ~ len(x) - i
    >>> x
    [1, 3, 4, 3]
    

    Timing results for lists of length 1000 and 100000 with 10% matching entries: 0.16 vs 0.25 ms, and 23 vs 123 ms.

    0 讨论(0)
  • 2020-11-21 23:54

    You can use a list comprehension:

    def remove_values_from_list(the_list, val):
       return [value for value in the_list if value != val]
    
    x = [1, 2, 3, 4, 2, 2, 3]
    x = remove_values_from_list(x, 2)
    print x
    # [1, 3, 4, 3]
    
    0 讨论(0)
  • 2020-11-21 23:54
    a = [1, 2, 2, 3, 1]
    to_remove = 1
    a = [i for i in a if i != to_remove]
    print(a)
    

    Perhaps not the most pythonic but still the easiest for me haha

    0 讨论(0)
提交回复
热议问题