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

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

    Here's how to do it inplace (without list comprehension):

    def remove_all(seq, value):
        pos = 0
        for item in seq:
            if item != value:
               seq[pos] = item
               pos += 1
        del seq[pos:]
    
    0 讨论(0)
  • 2020-11-22 13:19

    Consider:

    a = [1,2,2,3,4,5]
    

    To take out all occurrences, you could use the filter function in python. For example, it would look like:

    a = list(filter(lambda x: x!= 2, a))
    

    So, it would keep all elements of a != 2.

    To just take out one of the items use

    a.remove(2)
    
    0 讨论(0)
  • 2020-11-22 13:19

    Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:

    >>> a = [1, 2, 3, 4]
    >>> try:
    ...   a.remove(6)
    ... except ValueError:
    ...   pass
    ... 
    >>> print a
    [1, 2, 3, 4]
    >>> try:
    ...   a.remove(3)
    ... except ValueError:
    ...   pass
    ... 
    >>> print a
    [1, 2, 4]
    

    If you do this often, you can wrap it up in a function:

    def remove_if_exists(L, value):
      try:
        L.remove(value)
      except ValueError:
        pass
    
    0 讨论(0)
  • 2020-11-22 13:19

    Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.

    In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.

    In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it

    Then, Im used:

    c = len(list)-1
    for element in (reversed(list)):
        if condition(element):
            del list[c]
        c -= 1
    print(list)
    

    where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]

    Also You can do more pythonic using enumerate:

    for i, element in enumerate(reversed(list)):
        if condition(element):
            del list[(i+1)*-1]
    print(list)
    
    0 讨论(0)
  • 2020-11-22 13:20

    With a for loop and a condition:

    def cleaner(seq, value):    
        temp = []                      
        for number in seq:
            if number != value:
                temp.append(number)
        return temp
    

    And if you want to remove some, but not all:

    def cleaner(seq, value, occ):
        temp = []
        for number in seq:
            if number == value and occ:
                occ -= 1
                continue
            else:
                temp.append(number)
        return temp
    
    0 讨论(0)
  • 2020-11-22 13:21

    You can do

    a=[1,2,3,4]
    if 6 in a:
        a.remove(6)
    

    but above need to search 6 in list a 2 times, so try except would be faster

    try:
        a.remove(6)
    except:
        pass
    
    0 讨论(0)
提交回复
热议问题