为什么'0.00'在此 Python 代码中比较为不等于 0?



我的 IF ELSE 语句有什么问题?

如果不是条件,请执行 A。否则,执行 B。

但结果与我预期的完全不同。 :S

data['stock'] = ['0.02', '0.03', '0.04', '0.00', '0.05', '0.04', '0.05']
x = 0
y = len(data['Keywords'])
while x <= y - 1:
    if data['stock'][x] != 0:
        print data["stock"][x]
        a = a + 1
    else:
        print "hello"
        a = a + 1
Output:
0.02
0.03
0.04
0.00
0.05
0.04
0.05
'0.00'是一个

字符串。 0是一个数字。 这些是不平等的。

一个明显的问题是你的列表包含字符串,而你的代码需要数字。在Python中,你可以将0"0"进行比较(它们比较不相等)。

一种解决方法:

data['stock'] = [0.02, 0.03, 0.04, 0.00, 0.05, 0.04, 0.05]

此外,该循环看起来绝对不是Pythonic。第一步是这样改写它:

for x in range(len(data['Keywords'])):
    if data['stock'][x] != 0:
        print data["stock"][x]
    else:
        print "hello"

如果不使用 x 的值,而不是用于索引到列表中,则不需要计数器:

for val in data["stock"]:
    if val != 0:
        print val
    else:
        print "hello"

请注意,这假定data["Keywords"]具有相同的长度和data["stock"]。如果不是这种情况,则此代码不等同于您的代码。

最新更新