arrays - 为什么不计算 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
解决方案
如果两个变量指向同一个对象,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])
推荐阅读
- r - 如何计算有多少子字符串匹配列表的至少一个元素,只有当它们之前或之后没有否定?
- nativescript-vue - 无法使用 Nativescript-Vue GridLayout 显示项目列表
- java - Android:引用单个视图的多个变量?
- javascript - 如何在轮播中的上一个和下一个按钮中嵌入上一个和下一个图像
- javascript - 使用 GraphQL 查询 wordpress 插件 rest API
- python - 在 python 中将“2019 年 11 月 19 日,下午 12:00”转换为“2019-11-19T12:00”
- tensorflow - 通过字符串动态获取 TensorFlow 类型?
- javascript - 将 JSON 正文发送到侦听主机:端口
- asp.net-core-webapi - 如何格式化 Serilog 的 MS Sql Server Sink 中的 Level 列值
- c# - 如何在 Unity 中仅缩放 AR 场景中的一个游戏对象?