Remove list element without mutation

后端 未结 6 1372
无人及你
无人及你 2021-02-04 23:36

Assume you have a list

>>> m = [\'a\',\'b\',\'c\']

I\'d like to make a new list n that has everything except for a given

相关标签:
6条回答
  • 2021-02-05 00:14

    Another approach to list comprehension is numpy:

    >>> import numpy
    >>> a = [1, 2, 3, 4]
    >>> list(numpy.remove(a, a.index(3)))
    [1, 2, 4]
    
    0 讨论(0)
  • 2021-02-05 00:19

    I assume you mean that you want to create a new list without a given element, instead of changing the original list. One way is to use a list comprehension:

    m = ['a', 'b', 'c']
    n = [x for x in m if x != 'a']
    

    n is now a copy of m, but without the 'a' element.

    Another way would of course be to copy the list first

    m = ['a', 'b', 'c']
    n = m[:]
    n.remove('a')
    

    If removing a value by index, it is even simpler

    n = m[:index] + m[index+1:]
    
    0 讨论(0)
  • 2021-02-05 00:19

    You can create a new list without the offending element with a list-comprehension. This will preserve the value of the original list.

    l = ['a', 'b', 'c']
    [s for s in l if s != 'a']
    
    0 讨论(0)
  • 2021-02-05 00:24

    We can do it without using in built remove function and also without creating new list variable

    Code:

    # List m
    m = ['a', 'b', 'c']
    
    # Updated list m, without creating new list variable
    m = [x for x in m if x != a]
    
    print(m)
    

    output

    >>> ['b', 'c']
    
    0 讨论(0)
  • 2021-02-05 00:29

    There is a simple way to do that using built-in function :filter .

    Here is ax example:

    a = [1, 2, 3, 4]
    b = filter(lambda x: x != 3, a)
    
    0 讨论(0)
  • 2021-02-05 00:34

    If the order is unimportant, you can use set (besides, the removal seems to be fast in sets):

    list(set(m) - set(['a']))
    
    0 讨论(0)
提交回复
热议问题