Python新手,遇到这个问题。
场景:我有一个包含多个未知整数的列表。我需要把它们拿出来,进行分类,提取出最频繁出现的。如果一个项目有多个实例,则应该首先选择较高的值。
到目前为止,我已经制作了一个字典来处理示例请求列表,但我不确定如何提取上述指定的键和值。
def frequency(requests):
freq = {}
for x in requests:
if (x in freq):
freq[x] += 1
else:
freq[x] = 1
print(freq) # provides expected result
#my attempt to sort dictionary and extract required values
sorted_freq = dict(sorted(freq.items(), key=lambda x:x[1], reverse=True))
print(sorted_freq) #printing the keys at this stage doesn't factor in if the key is bigger/smaller for items with same frequency
print(sorted_freq.keys())
return
requests = [2,3,6,5,2,7,2,3,6,5,2,7,11,2,77] #example of request
frequency(requests)
#Output for freq = {2: 5, 3: 2, 6: 2, 5: 2, 7: 2, 11: 1, 77: 1}
#Output for sorted_freq = {2: 5, 3: 2, 6: 2, 5: 2, 7: 2, 11: 1, 77: 1}
#Output for sorted_freq.keys = [2, 3, 6, 5, 7, 11, 77]
在上面,3,6,5 &7都有两次出现,类似地11 &都是同一件事。我要找的输出是[2,7,6,5,3,77,11]
我已经在上面添加了额外的打印来可视化问题,只需要在实际代码中最终打印。
不知道解决这个问题的最佳方法是什么,任何帮助都会很感激。由于
from collections import Counter
from itertools import groupby
requests = [2,3,6,5,2,7,2,3,6,5,2,7,11,2,77]
c = Counter(requests)
freq = list()
for i,g in groupby(c.items(), key=lambda t:t[1]):
freq.extend(sorted([j for j,k in g],reverse=True))
print(freq)
尽量使用内置插件,因为它们真的很有用,不要重新发明轮子:)
输出:
[2, 7, 6, 5, 3, 77, 11]