Python|计算第 N 个元组元素
有时,在使用Python时,我们可能会遇到需要计算特定元素的出现次数的问题。这种问题在处理记录时很常见。让我们讨论一种可以执行此任务的方式。
方法 #1:使用Counter()
+ 生成器表达式
上述功能的组合可用于完成此特定任务。在此,我们使用生成器表达式遍历特定索引并使用Counter()
计算计数。
# Python3 code to demonstrate working of
# Counting Nth tuple element
# using Counter() + generator expression
from collections import Counter
# initialize list
test_list = [('gfg', 0), ('is', 1), ('best', 2),
('gfg', 2), ('is', 0), ('for', 1),
('geeks', 2)]
# printing original list
print("The original list : " + str(test_list))
# initialize N
N = 1
# Counting Nth tuple element
# using Counter() + generator expression
res = dict(Counter(sub[N] for sub in test_list))
# printing result
print("The grouped Nth element frequency is : " + str(res))
输出 :
The original list : [(‘gfg’, 0), (‘is’, 1), (‘best’, 2), (‘gfg’, 2), (‘is’, 0), (‘for’, 1), (‘geeks’, 2)]
The grouped Nth element frequency is : {0: 2, 1: 2, 2: 3}
方法 #2:使用Counter() + map() + itemgetter()
上述功能的组合可以用来完成这个任务。在此,生成器表达式执行的任务由map() and itemgetter()
用于获取容器元素的索引。
# Python3 code to demonstrate working of
# Counting Nth tuple element
# using Counter() + map() + itemgetter()
from collections import Counter
from operator import itemgetter
# initialize list
test_list = [('gfg', 0), ('is', 1), ('best', 2),
('gfg', 2), ('is', 0), ('for', 1),
('geeks', 2)]
# printing original list
print("The original list : " + str(test_list))
# initialize N
N = 1
# Counting Nth tuple element
# using Counter() + map() + itemgetter()
res = dict(Counter(map(itemgetter(N), test_list)))
# printing result
print("The grouped Nth element frequency is : " + str(res))
输出 :
The original list : [(‘gfg’, 0), (‘is’, 1), (‘best’, 2), (‘gfg’, 2), (‘is’, 0), (‘for’, 1), (‘geeks’, 2)]
The grouped Nth element frequency is : {0: 2, 1: 2, 2: 3}