Python使用for循环,json,openweathermap api跳过结果

时间:2017-10-31 22:12:03

标签: python json loops iterator openweathermap

我在探索,学习时仍然是Python新手,今天我正在使用JSON并尝试跳过其他所有结果。如何跳过,传递或“继续”其他所有结果?我已经尝试过使用continue,iteration,islice,ranges和next(),但我似乎无法完成这个特定的行为。这是我的代码:

import requests, pytemperature, json

r = requests.get('http://samples.openweathermap.org/data/2.5/forecast?
lat=35&lon=139&appid=b1b15e88fa797225412429c1c50c122a1')
dict = r.json()
select_data = dict['list']

for box in select_data:
    if 'dt_txt' in box:
        print(box['dt_txt'], box['main']['temp_min'], box['main']  
 ['temp_max'], box['wind']['speed'], box['weather'][0]['description'])  
    else:
        print('no found')

在上面的链接中,您可以找到完整的JSON文件,但我的输出如下(总共~40行):

2017-11-01 00:00:00 284.786 285.03 1.4 clear sky
2017-11-01 03:00:00 281.496 281.68 1.6 clear sky
2017-11-01 06:00:00 279.633 279.75 1.06 clear sky

最终结果应该是

2017-11-01 00:00:00 284.786 285.03 1.4 clear sky
2017-11-01 06:00:00 279.633 279.75 1.06 clear sky

旁注:最后我试图打印日期,temp_min,temp_max,main和description。我将温度从开尔文转换为华氏温度,然后每天使用gmail向我发送短信给新的预测。提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

如果select_data是一个列表,则可以对其进行切片。

for box in select_data[::2]:
    if 'dt_txt' in box:
        print(box['dt_txt'], box['main']['temp_min'], box['main']  
 ['temp_max'], box['wind']['speed'], box['weather'][0]['description'])  
    else:
        print('no found')

[::2]是一种表示python检索列表中某些元素的符号,但它不是检索所有元素,而是使用两步。 Here是对其工作原理的一个很好的解释。

为了完整起见的一个例子:

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(a[::2])
[1, 3, 5]