首页 文章

从列表中删除所有出现的值?

提问于
浏览
264

在Python中, remove() 将删除列表中第一次出现的值 .

如何从列表中删除所有出现的值,而不对列表进行排序?

这就是我的想法 .

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> def remove_values_from_list(the_list, val):
        while val in the_list:
            the_list.remove(val)
>>> remove_values_from_list(x, 2)
>>> x
[1, 3, 4, 3]

20 回答

  • 0

    要删除所有重复的事件并在列表中保留一个:

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

    这是我用于Project Euler的函数:

    def removeOccurrences(e):
      return list(set(e))
    
  • 1
    p=[2,3,4,4,4]
    p.clear()
    print(p)
    []
    

    仅限Python 3

  • 361

    看看简单的解决方案

    解决方案1:

    >>> [i for i in x if i != 2]
    

    这将返回一个列表,其中包含 x 的所有元素,而不是 2

    解决方案2:

    >>> while 2 in x : x.remove(2)
    
  • 5

    你可以这样做

    while 2 in x:   
        x.remove(2)
    
  • 5

    这会修改列表吗?

    >>> x=[1,2,3,4,5,6,7,8]
    >>> x
    [1, 2, 3, 4, 5, 6, 7, 8]
    >>> x = [val for val in x if val not in [2,3,4]]
    >>> x
    [1, 5, 6, 7, 8]
    
  • -2

    我相信如果您不关心列表顺序,这可能比任何其他方式更快,如果您确实关注最终订单存储索引从原始和度假 .

    category_ids.sort()
    ones_last_index = category_ids.count('1')
    del category_ids[0:ones_last_index]
    
  • 165

    如果必须修改原始列表,则仍可以使用切片分配,同时仍使用有效的列表推导(或生成器表达式) .

    >>> x = [1, 2, 3, 4, 2, 2, 3]
    >>> x[:] = (value for value in x if value != 2)
    >>> x
    [1, 3, 4, 3]
    
  • 28
    a = [1, 2, 2, 3, 1]
    to_remove = 1
    a = [i for i in a if i != to_remove]
    print(a)
    

    也许不是最诡异的,但对我来说仍然是最简单的哈哈

  • 0

    出了什么问题:

    电机= ['1','2','2']对于电机中的i:如果i!='2':打印(i)打印(电机)

    使用anaconda

  • 8

    功能方法:

    2.x

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

    3.x

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

    要么

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

    以更抽象的方式重复第一篇文章的解决方案:

    >>> x = [1, 2, 3, 4, 2, 2, 3]
    >>> while 2 in x: x.remove(2)
    >>> x
    [1, 3, 4, 3]
    
  • 1

    针对具有1.000.000元素的列表/数组的Numpy方法和时序:

    时序:

    In [10]: a.shape
    Out[10]: (1000000,)
    
    In [13]: len(lst)
    Out[13]: 1000000
    
    In [18]: %timeit a[a != 2]
    100 loops, best of 3: 2.94 ms per loop
    
    In [19]: %timeit [x for x in lst if x != 2]
    10 loops, best of 3: 79.7 ms per loop
    

    Conclusion: 与列表理解方法相比,numpy快了27倍(在我的笔记本上)

    PS如果你想将常规Python列表 lst 转换为numpy数组:

    arr = np.array(lst)
    

    Build :

    import numpy as np
    a = np.random.randint(0, 1000, 10**6)
    
    In [10]: a.shape
    Out[10]: (1000000,)
    
    In [12]: lst = a.tolist()
    
    In [13]: len(lst)
    Out[13]: 1000000
    

    校验:

    In [14]: a[a != 2].shape
    Out[14]: (998949,)
    
    In [15]: len([x for x in lst if x != 2])
    Out[15]: 998949
    
  • 2
    for i in range(a.count(' ')):
        a.remove(' ')
    

    我相信更简单 .

  • 2

    First solution, using filter. Second solution, using list comprehension.

    #If we want to remove all 2.
    ls = [2, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 6, 2]
    
    # 1-filter takes two arguments(condition,sequence)
       ls = list(filter(lambda x: x != 2, ls))
    
    # 2-list comprehension
       ls = [x for x in ls if x != 2]
    
  • -1

    您可以使用列表理解:

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

    关于速度!

    import time
    s_time = time.time()
    
    print 'start'
    a = range(100000000)
    del a[:]
    print 'finished in %0.2f' % (time.time() - s_time)
    # start
    # finished in 3.25
    
    s_time = time.time()
    print 'start'
    a = range(100000000)
    a = []
    print 'finished in %0.2f' % (time.time() - s_time)
    # start
    # finished in 2.11
    
  • 10

    上面的所有答案(除了Martin Andersson的)都会创建一个没有所需项目的新列表,而不是从原始列表中删除项目 .

    >>> import random, timeit
    >>> a = list(range(5)) * 1000
    >>> random.shuffle(a)
    
    >>> b = a
    >>> print(b is a)
    True
    
    >>> b = [x for x in b if x != 0]
    >>> print(b is a)
    False
    >>> b.count(0)
    0
    >>> a.count(0)
    1000
    
    >>> b = a
    >>> b = filter(lambda a: a != 2, x)
    >>> print(b is a)
    False
    

    如果您对列表有其他引用,这可能很重要 .

    要修改列表,请使用这样的方法

    >>> def removeall_inplace(x, l):
    ...     for _ in xrange(l.count(x)):
    ...         l.remove(x)
    ...
    >>> removeall_inplace(0, b)
    >>> b is a
    True
    >>> a.count(0)
    0
    

    就速度而言,我的笔记本电脑上的结果是(所有5000个条目列表中删除了1000个条目)

    • 列表理解 - ~400us

    • 过滤器 - 约900us

    • .remove()循环 - 50ms

    所以.remove循环慢了大约100倍........嗯,也许需要一种不同的方法 . 我发现最快的是使用列表推导,但随后替换原始列表的内容 .

    >>> def removeall_replace(x, l):
    ....    t = [y for y in l if y != x]
    ....    del l[:]
    ....    l.extend(t)
    
    • removeall_replace() - 450us
  • 0

    以可读性为代价,我认为这个版本稍微快一些,因为它不会强制重新检查列表,因此无论如何都要执行完全相同的工作删除:

    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

    如果你没有内置的 filter 或者不想使用额外的空间而你需要线性解决方案......

    def remove_all(A, v):
        k = 0
        n = len(A)
        for i in range(n):
            if A[i] !=  v:
                A[k] = A[i]
                k += 1
    
        A = A[:k]
    
  • 3

    从Python列表中删除所有出现的值

    lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
    def remove_values_from_list():
        for list in lists:
          if(list!=7):
             print(list)
    remove_values_from_list()
    

    结果: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

    或者,

    lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
    def remove_values_from_list(remove):
        for list in lists:
          if(list!=remove):
            print(list)
    remove_values_from_list(7)
    

    结果: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

相关问题