我试图查看多个来源,看看哪个来源有特定条目。
我的输入如下:
json_str2 = urllib2.urlopen(URL2).read()
u = json.loads(json_str2)
#load all five results
One = u['flightStatuses'][0]
Two = u['flightStatuses'][1]
Three = u['flightStatuses'][2]
Four = u['flightStatuses'][3]
Five = u['flightStatuses'][4]
我的if
语句正常工作,我得到了正确的结果:
if One['flightNumber'] == str(FlEnd):
fnumber = One['flightId']
print fnumber
但是当我添加elif:
时,即使第一个语句是True
,答案也是错误的(没有)。
我不明白elif
为什么不起作用?
# if statement checks each result to define flightId, needed for tracking.
if One['flightNumber'] == str(FlEnd):
fnumber = One['flightId']
elif Two['flightNumber'] == str(FlEnd):
fnumber = Two['flightId']
print fnumber
答案 0 :(得分:3)
你应该把它写成五个飞行状态的循环,而不是使用五个变量和五个条件。
results = json.loads(urllib2.urlopen(URL2).read())['flightStstuses']
for result in results:
if result['flightNumber'] == str(FlEnd):
fnumber = result['flightId']
break
else:
fnumber = None
print fnumber