python - 高效地从生成器中提取数据
问题描述
我只是在学习 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')
解决方案
您的代码相当有效,但可以精简为:
代码:
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
推荐阅读
- terraform - 需要权限 iam.serviceAccounts.setIamPolicy 才能对服务帐户执行此操作
- qt - 在 travis-ci linux 上安装 Qt5.12
- gis - 在 netlogo 6.2 中加载栅格数据时出错
- reactjs - 在组件上使用 .map 会导致组件返回“渲染中没有返回任何内容......”错误
- reactjs - webpack、webpack-obfuscator 和 webpack-cli 版本地狱
- jestjs - 开玩笑的测试快照因 last-modified、etag 和其他有意更改但无意义的值而失败
- python - 如何在pyqt5中使用带有嵌入式图形的matplotlib自定义样式
- spring - 会话范围 bean 的设置器在 RestController 中不起作用
- node.js - 如何保护无服务器应用程序中未经身份验证的用户访问的端点
- node.js - Heroku 后端 Node.js 和 Netlify 前端反应应用程序已被 CORS 策略阻止: