我熟悉基于单个字段将记录分组在一起:
from itertools import groupby
from operator import itemgetter
rows.sort(key=itemgetter('some_field')
groups_list = []
for data, items in groupby(rows, key=itemgetter('some_field'):
group_list = []
for item in items:
group_list.append(item)
groups_list.append(group_list
如果我想基于两个字段将记录分组在一起而不必迭代它们两次,我怎么能完成这个?
答案 0 :(得分:0)
您可以使用匿名函数对这两个字段进行排序和分组:
f = lambda x: (x['field1'], x['field2'])
rows.sort(key=f)
groups_list = []
for data, items in groupby(rows, key=f):
...
或者更新您的itemgetter
以获取这两个字段:
f = itemgetter('field1', 'field2')
rows.sort(key=f)
groups_list = []
for data, items in groupby(rows, key=f):
...