Tin*_*ing 0 python if-statement
我的IF ELSE声明有什么问题?
如果没有条件,请做A. ELSE,做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
Run Code Online (Sandbox Code Playgroud)
一个明显的问题是您的列表包含字符串,您的代码需要数字.在Python中,你被允许进行比较0,以"0"(他们比较不等).
解决它的一种方法:
data['stock'] = [0.02, 0.03, 0.04, 0.00, 0.05, 0.04, 0.05]
Run Code Online (Sandbox Code Playgroud)
而且,那个循环看起来绝对不是Pythonic.第一步是将其改为:
for x in range(len(data['Keywords'])):
if data['stock'][x] != 0:
print data["stock"][x]
else:
print "hello"
Run Code Online (Sandbox Code Playgroud)
如果您不使用x除索引到列表之外的值,则不需要计数器:
for val in data["stock"]:
if val != 0:
print val
else:
print "hello"
Run Code Online (Sandbox Code Playgroud)
请注意,这假设data["Keywords"]具有相同的长度和data["stock"].如果不是这种情况,则此代码与您的代码不同.