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

Python skipping over result using for loop, json, openweathermap api

我在探索、学习时对 Python 还是个新手,今天我正在使用 JSON 并试图跳过所有其他结果。如何跳过、传递或 "continue" 所有其他结果?我试过使用 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')

在上面 link 您可以找到完整的 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、主要内容和描述。我将把温度从开尔文转换为华氏,然后每天使用 gmail 给我发短信给我新的预报。预先感谢您的帮助!

如果 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]