Python – 元组中的最大频率
有时,在使用Python元组时,我们可能会遇到需要在元组中找到最大频率元素的问题。元组是非常流行的容器,这类问题在 Web 开发领域很常见。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = (6, 7, 10, 11, 10)
Output : 10
Input : test_tuple = (5, 5, 5)
Output : 5
方法 #1:使用count()
+ 循环
上述功能的组合可以用来解决这个问题。这是解决此问题的蛮力方法。在此,我们使用 count() 来执行元素计数。
# Python3 code to demonstrate working of
# Maximum frequency in Tuple
# Using loop + count()
# initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Maximum frequency in Tuple
# Using loop + count()
cnt = 0
res = test_tuple[0]
for ele in test_tuple:
curr_freq = test_tuple.count(ele)
if(curr_freq> cnt):
cnt = curr_freq
res = ele
# printing result
print("Maximum element frequency tuple : " + str(res))
输出 :
The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6
方法 #2:使用max() + Counter()
+ lambda
上述功能的组合可以用来解决这个问题。在此,我们使用 Counter() 来查找所有元素的频率,并使用 max() 来查找它的最大值。
# Python3 code to demonstrate working of
# Maximum frequency in Tuple
# Using max() + Counter() + lambda
from collections import Counter
# initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Maximum frequency in Tuple
# Using max() + Counter() + lambda
res = max(Counter(test_tuple).items(), key = lambda ele : ele[1])
# printing result
print("Maximum element frequency tuple : " + str(res[0]))
输出 :
The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6