Python – 按列表中的第 K 列对记录进行分组
有时,在使用Python列表时,我们可能会遇到需要根据某些参数对记录进行分组的问题。一个这样的参数可以在元组的第 K 个元素上。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + defaultdict()
上述方法的组合可用于执行此任务。在此,我们使用 defaultdict 将元组存储在不同的列表中,基于第 K 列,使用循环进行迭代。
# Python3 code to demonstrate
# Group records by Kth column in List
# using loop + defaultdict()
from collections import defaultdict
# Initializing list
test_list = [('Gfg', 1), ('is', 2), ('Gfg', 3), ('is', 4), ('best', 5)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 0
# Group records by Kth column in List
# using loop + defaultdict()
temp = defaultdict(list)
for ele in test_list:
temp[ele[K]].append(ele)
res = list(temp.values())
# printing result
print ("The list after grouping : " + str(res))
输出 :
The original list is : [('Gfg', 1), ('is', 2), ('Gfg', 3), ('is', 4), ('best', 5)]
The list after grouping : [[('Gfg', 1), ('Gfg', 3)], [('is', 2), ('is', 4)], [('best', 5)]]
方法 #2:使用itemgetter() + groupby()
+ 列表理解
上述函数的组合也可以使用上述功能进行。其中,itemgetter 用于选择第 K 列,groupby() 用于分组,列表推导用于编译结果。
# Python3 code to demonstrate
# Group records by Kth column in List
# using itemgetter() + list comprehension + groupby()
from operator import itemgetter
from itertools import groupby
# Initializing list
test_list = [('Gfg', 1), ('is', 2), ('Gfg', 3), ('is', 4), ('best', 5)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 0
# Group records by Kth column in List
# using loop + defaultdict()
temp = itemgetter(K)
res = [list(val) for key, val in groupby(sorted(test_list, key = temp), temp)]
# printing result
print ("The list after grouping : " + str(res))
输出 :
The original list is : [('Gfg', 1), ('is', 2), ('Gfg', 3), ('is', 4), ('best', 5)]
The list after grouping : [[('Gfg', 1), ('Gfg', 3)], [('is', 2), ('is', 4)], [('best', 5)]]