简体   繁体   中英

Most common value in flat list

What are some ways to get the most common value in a list?

l = [1,2,2]

So far I'm doing:

Counter(l).most_common()[0][0]

But I was wondering if there was a list method or something 'simpler' to do this?

That's pretty much as good as it gets - although I'd suggest using .most_common(1) which will be more efficient* than .most_common() and use it like so:

(value, count), = Counter(sequence).most_common(1)

*Source from collections.Counter :

if n is None:
    return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))

You can use max with list.count , but it's not efficient as your current solution:

>>> l = [1, 2, 2]
>>> max(set(l), key=l.count)
2

This is almost equivalent to what @JonClement 's solution does

>>> from collections import Counter
>>> l = [1,2,2]
>>> c = Counter(l)
>>> max(c, key=c.get)
2

As heapq.nlargest will run

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)]

in this specific case where n=1 which performs the same as above just without the list of a single tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM