我有一个这样的字典列表:
a = [
{'user_id':'111','clean_label':'VIR SEPA'},
{'user_id':'112','clean_label':'VIR SEPA'},
{'user_id':'111','clean_label':'VIR SEPA'},
]
和我想要的
a = [
[
{'user_id':'111','clean_label':'VIR SEPA'},
{'user_id':'111','clean_label':'VIR SEPA'}
],
[
{'user_id':'112','clean_label':'VIR SEPA'}
]
]
我尝试了从itertools中排序和分组:
sorted(a,key=lambda x: (x['user_id'],x['clean_label']))
[ [tr for tr in tr_per_user_id_clean_label] for key, tr_per_user_id_clean_label in itertools.groupby(a, key=lambda x: (x['user_id'], x['clean_label'])) ]
但是我明白了:
[[{'user_id': '111', 'clean_label': 'VIR SEPA'}],
[{'user_id': '112', 'clean_label': 'VIR SEPA'}],
[{'user_id': '111', 'clean_label': 'VIR SEPA'}]]
有人能帮我吗??*编辑:当我排序a:
[{'user_id': '111', 'clean_label': 'VIR SEPA'},
{'user_id': '111', 'clean_label': 'VIR SEPA'},
{'user_id': '112', 'clean_label': 'VIR SEPA'}]
sorted()
返回一个新列表,并且不改变现有列表的顺序。选择a.sort()
或groupby(sorted(a, key=...), key=...)
但是,为什么要排序呢?您可以使用字典作为累加器,如mozway的答案。
itertools.groupby
并不是真正理想的工具。
您可以使用defaultdict
以O(n)复杂度实现您的目标(与需要排序的groupby
相比为O(n log n)):
from collections import defaultdict
dd = defaultdict(list)
for d in a:
dd[(d['user_id'], d['clean_label'])].append(d)
out = list(dd.values())
替代setdefault
:
dd = {}
for d in a:
dd.setdefault((d['user_id'], d['clean_label']), []).append(d)
out = list(dd.values())
输出:
[[{'user_id': '111', 'clean_label': 'VIR SEPA'},
{'user_id': '111', 'clean_label': 'VIR SEPA'}],
[{'user_id': '112', 'clean_label': 'VIR SEPA'}]]
如果输出需要按user_id:
排序out = sorted(dd.values(),
key=lambda x: (int(x[0]['user_id']), int(x[0]['clean_label'])))