Python 平面列表中最常见的值
获取列表中最常见值的方法有哪些Python 平面列表中最常见的值,python,list,Python,List,获取列表中最常见值的方法有哪些 l = [1,2,2] 到目前为止,我正在做: Counter(l).most_common()[0][0] 但我想知道是否有一种列表方法或更“简单”的方法来实现这一点?您可以与一起使用,但它不如您当前的解决方案有效: >>> l = [1, 2, 2] >>> max(set(l), key=l.count) 2 虽然我建议使用.most\u common(1)这将比更有效*。most\u common()并像这样使用它
l = [1,2,2]
到目前为止,我正在做:
Counter(l).most_common()[0][0]
但我想知道是否有一种列表方法或更“简单”的方法来实现这一点?您可以与一起使用,但它不如您当前的解决方案有效:
>>> l = [1, 2, 2]
>>> max(set(l), key=l.count)
2
虽然我建议使用
.most\u common(1)
这将比更有效*。most\u common()
并像这样使用它:
(value, count), = Counter(sequence).most_common(1)
*来源于集合。计数器:
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
这几乎等同于@JonClement的解决方案
>>> from collections import Counter
>>> l = [1,2,2]
>>> c = Counter(l)
>>> max(c, key=c.get)
2
照常
在这种特殊情况下,
n=1
执行与上述相同的操作,但没有一个元组列表。如果只在最常见的后面,请使用计数器(l)。最常见的(1)
作为计数器
类优化该用例
if n == 1:
it = iter(iterable)
head = list(islice(it, 1))
if not head:
return []
if key is None:
return [max(chain(head, it))]
return [max(chain(head, it), key=key)]