在python中,如何根据多个字段将记录组合​​在一起?

时间:2017-07-20 20:03:47

标签: python itertools

我熟悉基于单个字段将记录分组在一起:

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

如果我想基于两个字段将记录分组在一起而不必迭代它们两次,我怎么能完成这个?

1 个答案:

答案 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):
     ...