【问题标题】:Efficiently extracting data from a generator高效地从生成器中提取数据
【发布时间】:2019-01-06 02:56:42
【问题描述】:

我只是在学习 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')

【问题讨论】:

    标签: python dictionary generator


    【解决方案1】:

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

    代码:

    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
    

    【讨论】:

      【解决方案2】:

      如果您指的是计算效率,则没有太大的改进空间。

      如果您的意思是更短的代码行,temp= (next(res)) 部分(与在代码中提取数据有关)似乎已经很短了。

      【讨论】:

        【解决方案3】:

        noaa_sdk 包的示例文档大量使用循环。如果您只是学习 Python,我建议您尝试使用面向循环的样式。

        from datetime import datetime
        
        from noaa_sdk import noaa
        
        def to_freedom_degrees(temp_c):
            return 32.0 + 9.0 / 5.0 * temp_c
        
        date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        observations = noaa.NOAA().get_observations('25311', 'US', start=date, end=None, num_of_stations=1)
        
        for observation in observations:
            temp_c = observation['temperature']
            temp_f = to_freedom_degrees(temp_c)
            print(temperature, ' F')
            # I only want one temperature
            break
        else:
            print('No temperature found!')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-17
          • 2021-08-05
          • 2018-08-18
          • 2013-01-06
          • 1970-01-01
          • 2020-05-31
          • 2014-06-01
          • 1970-01-01
          相关资源
          最近更新 更多