Python|通过元组键聚合值
有时,在处理记录时,我们可能会遇到需要对相似键进行分组并聚合相似键的值的问题。这可以应用于任何类型的评分。让我们讨论可以执行此任务的某些方式。
方法 #1:使用Counter()
+ 生成器表达式
上述功能的组合可用于执行此特定任务。在此,我们需要首先组合相似的关键元素,聚合任务由Counter()
执行。
# Python3 code to demonstrate working of
# Aggregate values by tuple keys
# using Counter() + generator expression
from collections import Counter
# initialize list
test_list = [('gfg', 50), ('is', 30), ('best', 100),
('gfg', 20), ('best', 50)]
# printing original list
print("The original list is : " + str(test_list))
# Aggregate values by tuple keys
# using Counter() + generator expression
res = list(Counter(key for key, num in test_list
for idx in range(num)).items())
# printing result
print("List after grouping : " + str(res))
输出 :
The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]
List after grouping : [('best', 150), ('gfg', 70), ('is', 30)]
方法#2:使用groupby() + map() + itemgetter() + sum()
上述功能的组合也可用于执行此特定任务。在此,我们使用 groupby() 对元素进行分组,键的索引由 itemgetter 决定。加法(聚合)任务由 sum() 执行,所有元组的逻辑扩展由 map() 处理。
# Python3 code to demonstrate working of
# Aggregate values by tuple keys
# using groupby() + map() + itemgetter() + sum()
from itertools import groupby
from operator import itemgetter
# initialize list
test_list = [('gfg', 50), ('is', 30), ('best', 100),
('gfg', 20), ('best', 50)]
# printing original list
print("The original list is : " + str(test_list))
# Aggregate values by tuple keys
# using groupby() + map() + itemgetter() + sum()
res = [(key, sum(map(itemgetter(1), ele)))
for key, ele in groupby(sorted(test_list, key = itemgetter(0)),
key = itemgetter(0))]
# printing result
print("List after grouping : " + str(res))
输出 :
The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]
List after grouping : [('best', 150), ('gfg', 70), ('is', 30)]