在不使用集合的情况下对事件进行计数 [英] Counting occurrences without using collections.Counter
本文介绍了在不使用集合的情况下对事件进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检索列表中最频繁和不频繁的元素。
I am trying to retrieve the most frequent and less frequent elements in a list.
frequency([13,12,11,13,14,13,7,11,13,14,12,14,14])
我的输出是:
([7], [13, 14])
我尝试过:
import collections
s = [13,12,11,13,14,13,7,11,13,14,12,14,14]
count = collections.Counter(s)
mins = [a for a, b in count.items() if b == min(count.values())]
maxes = [a for a, b in count.items() if b == max(count.values())]
final_vals = [mins, maxes]
但是我不知道不想使用 collections
模块并尝试一种更加面向逻辑的解决方案。
您能帮我没有收藏吗?
But I don't want to use the collections
module and try a more logic oriented solution.
Can you please help me to do it without collections?
推荐答案
您可以使用 try
和除了
方法和 dict
来模拟 Counter
。
You could use a try
and except
approach with a dict
to emulate a Counter
.
def counter(it):
counts = {}
for item in it:
try:
counts[item] += 1
except KeyError:
counts[item] = 1
return counts
或者您可以使用 dict.get
,默认值为 0
:
def counter(it):
counts = {}
for item in it:
counts[item] = counts.get(item, 0) + 1
return counts
您应该执行 min()
和 max()
,以避免重复计算该数量(该函数现在为 O(n)
而不是 O(n ^ 2)
:
And you should do the min()
and max()
outside the comprehensions to avoid repeatedly calculating that quantity (the function is now O(n)
instead of O(n^2)
:
def minimum_and_maximum_frequency(cnts):
min_ = min(cnts.values())
max_ = max(cnts.values())
min_items = [k for k, cnt in cnts.items() if cnt == min_]
max_items = [k for k, cnt in cnts.items() if cnt == max_]
return min_items, max_items
然后将按预期工作:
>>> minimum_and_maximum_frequency(counter([13,12,11,13,14,13,7,11,13,14,12,14,14]))
([7], [13, 14])
这篇关于在不使用集合的情况下对事件进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文