我试图检索列表中最常见和较不频繁的元素.
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]
但我不想使用集合模块并尝试更加面向逻辑的解决方案.
没有收藏,你可以帮我做吗?
解决方法:
您可以使用带有dict的try和except方法来模拟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):
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])