要找到最常见的,我知道我可以使用这样的事情:获取最不常见的元素阵列
most_common = collections.Counter(array).most_common(to_find)
不过,我似乎无法找到任何可比性,寻找最不常见的元素。
请问我可以得到有关如何操作的建议。
要找到最常见的,我知道我可以使用这样的事情:获取最不常见的元素阵列
most_common = collections.Counter(array).most_common(to_find)
不过,我似乎无法找到任何可比性,寻找最不常见的元素。
请问我可以得到有关如何操作的建议。
借款collections.Counter.most_common
源和反相酌情:
from operator import itemgetter
import heapq
import collections
def least_common_values(array, to_find=None):
counter = collections.Counter(array)
if to_find is None:
return sorted(counter.items(), key=itemgetter(1), reverse=False)
return heapq.nsmallest(to_find, counter.items(), key=itemgetter(1))
>>> data = [1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4]
>>> least_common_values(data, 2)
[(1, 2), (2, 4)]
>>> least_common_values([1,1,2,3,3])
[(2, 1), (1, 2), (3, 2)]
>>>
most_common
没有任何参数返回全部条目,从最常见到最少排序。
所以要找到最不常见的,从另一端开始看。
def least_common_values(array, to_find):
"""
>>> least_common_values([1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4], 2)
[(1, 2), (2, 4)]
"""
counts = collections.Counter(array)
return list(reversed(counts.most_common()[-to_find:]))
非常好。谢谢。 – jimy 2011-01-20 03:21:05
什么
least_common = collections.Counter(array).most_common()[-1]
您可以使用一键功能:
>>> data=[1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4]
>>> min(data,key=lambda x: data.count(x))
1
>>> max(data,key=lambda x: data.count(x))
4
我想你需要这个:
least_common = collections.Counter(array).most_common()[:-to_find-1:-1]
我建议如下,
least_common = collections.Counter(array).most_common()[len(to_find)-10:len(to_find)]
基于这个答案最常见的元素:https://stackoverflow.com/a/1518632
下面是在列表中获取最不常见的元素的一个班轮:
def least_common(lst):
return min(set(lst), key=lst.count)
啊我很好,我现在明白了。谢谢。 – jimy 2011-01-20 03:19:30