首页 > 解决方案 > 高效地从生成器中提取数据

问题描述

我只是在学习 python,我想知道是否有更好的方法从 res 变量中提取最新的温度。

from noaa_sdk import noaa
from datetime import datetime
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
n = noaa.NOAA()
res = n.get_observations('25311', 'US', start=date, end=None, num_of_stations=1)
temp= (next(res))
value =(temp.get('temperature'))
temperature = (value['value'])
temperature = temperature*9/5+32
print(temperature, ' F')

标签: pythondictionarygenerator

解决方案


您的代码相当有效,但可以精简为:

代码:

from noaa_sdk import noaa
import datetime as dt

date = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
res = noaa.NOAA().get_observations('25311', 'US', start=date)
print('{:.1f} F'.format( next(res)['temperature']['value'] * 9 / 5 + 32))

结果:

44.1 F

推荐阅读