首页 > 解决方案 > 为什么不计算 0.0?

问题描述

试图制作一个将零放在最后的列表。它忽略了0.0,它也需要放在最后作为0。为什么会这样?

尝试使用float(0)/ 0.0. 如果我将它更改为不同的整数而不是 0.0,它会起作用。

期望的输出[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

def move_zeros(array):
    count = 0
    for x in array: #counts how many zeros
        if x is 0 or float(0):
            count+=1
    array = [x for x in array if x is not 0] # removes all zeros
    array = [x for x in array if x is not float(0)]
    for y in range(count):
        array.append(0) #tacks zero to the end of list

    print(array)

move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9])

预计可以工作,但它忽略了0.0

标签: arrayspython-3.xsorting

解决方案


如果两个变量指向同一个对象,is 将返回 True,如果变量引用的对象相等,则 ==。

有关和之间区别的更详细说明,请参阅这个出色的答案。is==

如其他答案所述,您应该使用==and!=在您的情况下,因为您正在检查是否相等,而不是两个对象是否是内存中的相同对象。

这是您的代码,已修复错误:

def move_zeros(array):
    count = 0
    result = []
    for x in array: #counts how many zeros
        if x == 0 or x == float(0):
            count+=1

        elif x is not False and x is not None:
            result.append(x)

    for y in range(count):
        result.append(0) #tacks zero to the end of list

    print(result)

move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9])

推荐阅读