Python|对相似记录进行分组和计数
有时,在处理记录时,我们可能会遇到需要收集和维护记录中的计数器值的问题。这种应用程序在 Web 开发领域很重要。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + Counter() + set()
可以使用上述功能的组合来完成此任务。在此,我们运行一个循环来捕获每个元组并添加到 set 并检查它是否已经存在,然后增加并添加一个计数器值。累积计数是通过使用Counter()
来实现的。
# Python3 code to demonstrate working of
# Group and count similar records
# using Counter() + loop + set()
from collections import Counter
# initialize list
test_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ),
('is', ), ('for', ), ('geeks', )]
# printing original list
print("The original list : " + str(test_list))
# Group and count similar records
# using Counter() + loop + set()
res = []
temp = set()
counter = Counter(test_list)
for sub in test_list:
if sub not in temp:
res.append((counter[sub], ) + sub)
temp.add(sub)
# printing result
print("Grouped and counted list is : " + str(res))
The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]
Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]
方法 #2:使用Counter() + list comprehension + items()
这是一种线性方法,建议用于编程。循环的任务由列表理解处理,并且 items() 用于访问 Counter 转换字典的所有元素以允许计算。
# Python3 code to demonstrate working of
# Group and count similar records
# using Counter() + list comprehension + items()
from collections import Counter
# initialize list
test_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ),
('is', ), ('for', ), ('geeks', )]
# printing original list
print("The original list : " + str(test_list))
# Group and count similar records
# using Counter() + list comprehension + items()
res = [(counter, ) + ele for ele, counter in Counter(test_list).items()]
# printing result
print("Grouped and counted list is : " + str(res))
The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]
Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]