繁体   English   中英

使用列表值的字典理解

[英]dictionary comprehension using list values

我想使用字典/列表理解来创建字典多个列表。

这是我的 3 个列表:

city_list = ['new york','boston']
times = ['2021-01-01 19:00:00','2021-01-01 20:00:00']
weather_parameters = ['forecastTimeUtc', 'airtemperature', 'condition']

我想创建一个看起来像这样的字典:

{'new york':[{'forecastTimeUtc': '2021-01-01 20:00:00', 'airTemperature': 0, 'conditionCode': 0}, {'forecastTimeUtc': '2021-01-01 21:00:00', 'airTemperature': 0, 'conditionCode': 0}], 

'boston': [{'forecastTimeUtc': '2021-01-01 20:00:00', 'airTemperature': 0, 'conditionCode': 0}, {'forecastTimeUtc': '2021-01-01 21:00:00', 'airTemperature': 0, 'conditionCode': 0}]}

挑战是根据“forecastTimeUtc”内的值数量来乘以城市之后的列表。

默认情况下,键“airTemperature”和“conditionCode”的其他值应保持为 0。

通常,我们会在列表推导式简洁且使您的代码优雅时使用它们。 我担心想要一个字典理解会让你的代码的读者感到困惑,我建议构建多个嵌套的 for 循环。

尽管如此,这是一个满足您需求的字典压缩:

{city:[{weather_parameter: (time if weather_parameter == 'forecastTimeUtc' else 0) for weather_parameter in weather_parameters} for time in times] for city in city_list}

分步过程

没有任何列表理解,代码非常繁重

weather_per_city = {}
for city in city_list:
    params_list = []
    for time in times:
        param_dict = {}
        for weather_parameter in weather_parameters:
            if weather_parameter == 'forecastTimeUtc':
                param_dict[weather_parameter] = time
            else:    
                param_dict[weather_parameter] = 0
        params_list.append(param_dict)
    weather_per_city[city] = params_list

仍然没有列表理解,但使用三元运算符开始简化

weather_per_city = {}
for city in city_list:
    params_list = []
    for time in times:
        param_dict = {}
        for weather_parameter in weather_parameters:
            param_dict[weather_parameter] = time if weather_parameter == 'forecastTimeUtc' else 0
        params_list.append(param_dict)
    weather_per_city[city] = params_list

第一个字典理解:

weather_per_city = {}
for city in city_list:
    params_list = []
    for time in times:
        param_dict = {weather_parameter:(time if weather_parameter == 'forecastTimeUtc' else 0) for weather_parameter in weather_parameters}
        params_list.append(param_dict)
    weather_per_city[city] = params_list

并带有第二个理解(字典+列表):

weather_per_city = {}
for city in city_list:
    params_list = [{weather_parameter:(time if weather_parameter == 'forecastTimeUtc' else 0) for weather_parameter in weather_parameters} for time in times]
    weather_per_city[city] = params_list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM