Python – 元组中的元素频率
给定一个元组,找出每个元素的频率。
Input : test_tup = (4, 5, 4, 5, 6, 6, 5)
Output : {4: 2, 5: 3, 6: 2}
Explanation : Frequency of 4 is 2 and so on..
Input : test_tup = (4, 5, 4, 5, 6, 6, 6)
Output : {4: 2, 5: 2, 6: 3}
Explanation : Frequency of 4 is 2 and so on..
方法 #1 使用 defaultdict()
在此,我们使用 defaultdict 执行获取所有元素并分配频率的任务,defaultdict 将每个元素映射到键,然后可以增加频率。
Python3
# Python3 code to demonstrate working of
# Elements frequency in Tuple
# Using defaultdict()
from collections import defaultdict
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
res = defaultdict(int)
for ele in test_tup:
# incrementing frequency
res[ele] += 1
# printing result
print("Tuple elements frequency is : " + str(dict(res)))
Python3
# Python3 code to demonstrate working of
# Elements frequency in Tuple
# Using Counter()
from collections import Counter
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# converting result back from defaultdict to dict
res = dict(Counter(test_tup))
# printing result
print("Tuple elements frequency is : " + str(res))
输出
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
方法 #2:使用 Counter()
这是解决此问题的直接方法。在这种情况下,我们只使用此函数,它返回容器中元素的频率,在本例中为元组。
Python3
# Python3 code to demonstrate working of
# Elements frequency in Tuple
# Using Counter()
from collections import Counter
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# converting result back from defaultdict to dict
res = dict(Counter(test_tup))
# printing result
print("Tuple elements frequency is : " + str(res))
输出
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}