如何找到列表中出现最少的元素?
为了找出最常见的元素,我知道可以用类似这样的代码:
most_common = collections.Counter(list).most_common(to_find)
不过,我似乎找不到类似的方法来找出最不常见的元素。
请问有没有什么建议可以帮我实现这个功能。
13 个回答
43
那关于这个呢
least_common = collections.Counter(array).most_common()[-1]
46
most_common
这个函数如果不带任何参数,就会返回所有的条目,并且是按照从最常见到最不常见的顺序排列的。
所以,如果你想找到最不常见的条目,只需要从相反的方向开始查看就可以了。
27
借用一下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)]
>>>