Python使用理解将基于特定键的多个字典列表合并为一个列表

时间:2019-01-10 06:51:28

标签: python

我有以下2个列表

entry1= [{'day': 'mon', 'temp': 5, 'wind': 10},{'day': 'tue', 'temp': 6, 'wind': 15}]

entry2= [{'day': 'mon', 'temp': 7, 'wind': 10},{'day': 'wed', 'temp': 8, 'wind': 25}]  

使用理解力,如何使用key = day添加字典,以使输出为

expectedoutput = [{'day': 'mon', 'temp': 12, 'wind': 20}, 
                   {'day': 'tue', 'temp': 6, 'wind': 15}, 
                   {'day': 'wed', 'temp': 8, 'wind': 25}]  

在这里,因为'mon'是剩下的两个键,即temp = [5 + 7]和wind = [10 + 10]

2 个答案:

答案 0 :(得分:0)

2个解决方案,用于该列表“条目”:

entry1= [{'day': 'mon', 'temp': 5, 'wind': 10},{'day': 'tue', 'temp': 6, 'wind': 15}]
entry2= [{'day': 'mon', 'temp': 7, 'wind': 10},{'day': 'wed', 'temp': 8, 'wind': 25}]
entries = [entry1,entry2]

A:一支班轮

expected_result = [{'day':day,'temp': sum([i['temp']for i in [item for sublist in entries for item in sublist] if i['day']==day]),'wind': sum([i['wind']for i in [item for sublist in entries for item in sublist] if i['day']==day])} for day in ['mon','tue','wed']]
print(expected_result)
>>> [{'day': 'mon', 'temp': 12, 'wind': 20}, {'day': 'tue', 'temp': 6, 'wind': 15}, {'day': 'wed', 'temp': 8, 'wind': 25}]

B:基本相同,但有一点扩展

flatten = lambda l: [item for sublist in l for item in sublist]
f = (flatten(entries)) # FLATTEN LIST


days = ['mon','tue','wed']
expected_result = [{'day':day,'temp': sum([i['temp'] for i in f if i['day']==day]),'wind': sum([i['wind'] for i in f if i['day']==day])} for day in days]
print(expected_result)



>>> [{'day': 'mon', 'temp': 12, 'wind': 20}, {'day': 'tue', 'temp': 6, 'wind': 15}, {'day': 'wed', 'temp': 8, 'wind': 25}]

我不推荐 A 解决方案,因为它效率不高

答案 1 :(得分:-1)

此示例根据您的答案词典名称使用列表理解。我不明白为什么需要列表理解,但是无论如何,您可以在这里进行搜索:

import {intersects} from 'ol/extent';

const features = tile.getFeatures();
const matches = [];
for (let i = 0, ii = features.length; i < ii; ++i) {
  const feature = features[i];
  if (intersects(extent, feature.getGeometry().getExtent()) {
    matches.push(feature);
  }
}

这与您的答案无关,只需输入键(在您的情况下为“ day”),便会生成字典列表,与有多少值无关(最后一个示例能够处理3个特定值,“ day” ,“风”和“温度”,现在没有限制了):

def merge(dicts):
    my_dict = {}
    for i in dicts:
        day = i['day']
        if day in my_dict:
            my_dict[day][0] += i['temp']
            my_dict[day][1] += i['wind']
        else:
            my_dict[day] = [i['temp'], i['wind']]
    return [{'day': i, 'temp': my_dict[i][0], 'wind': my_dict[i][1]} for i in my_dict]