简体   繁体   English

从列表中删除其他元素时从列表中删除“假”

[英]'False' is removed from the list when removing other elements from list

I wrote a function to remove all zeroes from a list of elements with different datatypes.我写了一个 function 从具有不同数据类型的元素列表中删除所有零。 But while removing the zeroes.但是在删除零的同时。 The boolean value 'False' is also removed. boolean 值“False”也被删除。 But when I change it to 'True' it is not removed.但是当我将其更改为“真”时,它不会被删除。 I tried many different methods for doing this, but the result is the same.我尝试了许多不同的方法来做到这一点,但结果是一样的。

def move_zeros(array):
  for i in range(array.count(0)):
      array.remove(0)
  print(array)

move_zeros([0,1,None,2,False,1,0])

The output is output 是

[1, None, 2, 1] [1, 无, 2, 1]

How can I do this without getting the 'False' value removed?如何在不删除“False”值的情况下做到这一点?

False and True are equal to 0 and 1 respectively. False 和 True 分别等于 0 和 1。 If you want to remove 0 from a list without removing False, you could do this:如果你想从列表中删除 0 而不删除 False,你可以这样做:

my_list = [0,1,None,2,False,1,0]

my_list_without_zero = [x for x in my_list if x!=0 or x is False]

Since False is a single object, you can use is to check if a value is that specific object.由于False是单个 object,因此您可以使用is检查值是否是特定的 object。

You could try this code:你可以试试这段代码:

def move_zeros(array):
    for i in array:
        if (type(i) is int or type(i) is float) and i == 0:
            addr = array.index(i)
            del(array[addr])
    return array

This loops over all the items on the array, then checks if it is an integer or float and if it equals 0, then deletes it if it does.这会遍历数组上的所有项目,然后检查它是 integer 还是浮点数,如果它等于 0,则将其删除。 The reason False was getting removed is because False, when stored on the program, evaluates to 0. False 被删除的原因是,当 False 存储在程序中时,计算结果为 0。

You can try this:你可以试试这个:

def move_zeros(array):
    array = [x for x in array if x is False or x!=0]
    print(array)

move_zeros([0,1,None,2,False,1,0])

Or you can try this:或者你可以试试这个:

def move_zeros(array):
    newarray = []

    for x in array:
        if x is False or x!=0:
            newarray.append(x)

    print(newarray)

move_zeros([0,1,None,2,False,1,0])

after running any of this you should get [1, None, 2, False, 1]运行任何这些后,您应该得到[1, None, 2, False, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM