📜  Python - 连续元素最大频率

📅  最后修改于: 2022-05-13 01:54:27.791000             🧑  作者: Mango

Python - 连续元素最大频率

有时,在使用Python列表时,我们可能会遇到需要提取连续元素的最大频率的问题。这种问题可以作为在许多领域的应用出现,例如日间编程和竞争性编程。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + groupby()
上述功能的组合可用于执行此任务。在此,我们将所有连续元素分组,然后使用字典键与当前最大值进行比较来生成最大频率字典。

# Python3 code to demonstrate working of 
# Consecutive elements maximum frequencies
# Using loop + groupby()
from itertools import groupby
  
# initializing list
test_list = [5, 6, 7, 7, 6, 6, 5, 7]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Consecutive elements maximum frequencies
# Using loop + groupby()
res = {}
for key, val in groupby(test_list):
    sub = sum(1 for _ in val)
    if res.get(key, float('-inf')) < sub:
        res[key] = sub
  
# printing result 
print("The maximum frequencies : " + str(res)) 
输出 :
The original list is : [5, 6, 7, 7, 6, 6, 5, 7]
The maximum frequencies : {5: 1, 6: 2, 7: 2}

方法 #2:使用max() + list comprehension + set() + groupby()
上述功能的组合可用于解决此特定问题。在此,我们使用列表推导来执行比较,并使用 max() 找到最大元素。

# Python3 code to demonstrate working of 
# Consecutive elements maximum frequencies
# Using max() + list comprehension + set() + groupby()
from itertools import groupby
  
# initializing list
test_list = [5, 6, 7, 7, 6, 6, 5, 7]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Consecutive elements maximum frequencies
# Using max() + list comprehension + set() + groupby()
temp = list(set(test_list))
res = [{ele : max([len(list(val)) for key, val in groupby(test_list)
                                  if ele == key])} for ele in temp]
  
# printing result 
print("The maximum frequencies : " + str(res)) 
输出 :
The original list is : [5, 6, 7, 7, 6, 6, 5, 7]
The maximum frequencies : [{5: 1}, {6: 2}, {7: 2}]