d 合并后变成 new_d
d = [
{1: [12, 24]},
{1: [24, 36]},
{2: [111,222]}
]
new_d = [
{1: [12, 24, 36]},
{2: [111, 222]}
]
1
SuperMild 2017-03-05 14:23:35 +08:00 1
既然是列表,貌似一般就是遍历了吧,用 set 来做字典的 value 。最后再遍历一次把 set 转换为列表。
|
2
sagaxu 2017-03-05 14:36:00 +08:00 1
s = {k: set() for x in d for k,v in x.items()}
[s[k].update(v) for x in d for k,v in x.items()] {k: list(v) for k,v in s.items()} |
3
freestyle 2017-03-05 14:36:42 +08:00 1
|
4
popbones 2017-03-05 14:52:16 +08:00
[ {id: val} for (id, val) in [[(new_d, new_d.update({k: new_d.get(k, set()).union(set(v))})) for (k, v) in m.items()] for m in d][0][0][0].items() ]
|
5
popbones 2017-03-05 14:55:33 +08:00
new_d = {}
|
6
TJT 2017-03-05 22:14:14 +08:00
另外一种思路,前提是 d 得排序好
from itertools import groupby, chain [{k: [x for x, _ in groupby(sorted(chain(*[v[k] for v in g])))]} for k, g in groupby(d, lambda x: list(x.keys())[0])] |