为什么不计算0.0?

时间:2019-09-26 03:04:36

标签: arrays python-3.x sorting

尝试创建一个将零结尾的列表。并且它忽略了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

4 个答案:

答案 0 :(得分:1)

  如果两个变量指向同一个对象,

is将返回True;如果变量所引用的对象相等,则==。

有关is==之间差异的更详细说明,请参见this很好的答案。

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

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

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])

答案 1 :(得分:0)

您不应该使用is进行算术比较,并且不能像这样使用or合并两个条件。更改条件,如下所示:

if x == 0:

类似地修复列表理解中的条件(用x != 0代替x is not 0)。

答案 2 :(得分:0)

有一些问题:

  1. var newArr = [{"name":"john", "lastname":"doe"}] 评估两个对象是否在内存中是同一对象。您要使用is
  2. ==是无效代码。请改用if x is 0 or float(0)if x is 0 or x == float(0)。不过,您实际上并不需要区分if x in (0, float(0)0。只需使用float(0)if x == 0
  3. 您的列表理解中也出现了同样的问题。使用if not x或仅使用x != 0代替x

答案 3 :(得分:0)

关于or的注释:

  • x == 0 or x == float(0)有效
  • x in [0, float(0)]也可以工作并且更简单
    • [x for x in array if x != 0][x for x in array if x != float(0)]可以替换为[x for x in array if x not in [0, float(0)]]

简化功能

def move_zeros(array):
    zc = array.count(0)
    array = [x for x in array if x != 0] # removes all zeros
    array.extend([0 for _ in range(zc)])

    return array

test = [9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]

y = move_zeros(test)

print(y)

>>> [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

针对y验证test

from collections import Counter

print(test.count(0))
>>> 10

print(y.count(0))
>>> 10

print(len(test))
>>> 20

print(len(y))
>>> 20

test_dict = Counter(test)
print(test_dict)
>>> Counter({9: 4, 0.0: 10, 1: 4, 2: 1, 3: 1})

y_dict = Counter(test)
print(y_dict)
>>> Counter({9: 4, 0.0: 10, 1: 4, 2: 1, 3: 1})

或者:

test = [9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]

test_sorted = test.sort(reverse=True)
print(test_sorted)
>>> [9, 9, 9, 9, 3, 2, 1, 1, 1, 1, 0.0, 0, 0, 0, 0.0, 0, 0, 0, 0, 0]