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

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

    If you know what value to delete, here's a simple way (as simple as I can think of, anyway):

    a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
    while a.count(1) > 0:
        a.remove(1)
    

    You'll get [0, 0, 2, 3, 4]

    0 讨论(0)
  • 2020-11-22 13:21

    Say for example, we want to remove all 1's from x. This is how I would go about it:

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

    Now, this is a practical use of my method:

    def Function(List, Unwanted):
        [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
        return List
    x = Function(x, 1)
    print(x)
    

    And this is my method in a single line:

    [x.remove(1) for Item in range(x.count(1))]
    print(x)
    

    Both yield this as an output:

    [2, 3, 2, 3, 2, 3]
    

    Hope this helps. PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.

    0 讨论(0)
  • 2020-11-22 13:24
     list1=[1,2,3,3,4,5,6,1,3,4,5]
     n=int(input('enter  number'))
     while n in list1:
        list1.remove(n)
     print(list1)
    
    0 讨论(0)
提交回复
热议问题