如何获取列表中最不常见的元素? [英] How to get the least common element in a list?
本文介绍了如何获取列表中最不常见的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了找到最常见的,我知道我可以使用这样的东西:
To find the most common, I know I can use something like this:
most_common = collections.Counter(list).most_common(to_find)
然而,我似乎无法找到任何可比的东西,以找到最不常见的元素.
However, I can't seem to find anything comparable, for finding the least common element.
我能得到关于如何做的建议吗.
Could I please get recommendations on how to do.
推荐答案
借用 collections.Counter.most_common
的来源并适当反转:
Borrowing the source of collections.Counter.most_common
and inverting as appropriate:
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)]
>>>
这篇关于如何获取列表中最不常见的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文