【问题标题】:Python skipping over result using for loop, json, openweathermap apiPython使用for循环,json,openweathermap api跳过结果
【发布时间】:2017-10-31 22:12:03
【问题描述】:

在探索、学习的过程中,我对 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 和描述。我会将温度从开尔文转换为华氏温度,然后每天使用 gmail 向我发送新预测的短信。提前感谢您的帮助!

【问题讨论】:

    标签: python json loops iterator openweathermap


    【解决方案1】:

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

    【讨论】:

    • 完美,这正是我所需要的。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2013-02-01
    • 2021-08-23
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多