简体   繁体   中英

Find most common element

How can I print the most common element of a list without importing a library?

l=[1,2,3,4,4,4]

So I want the output to be 4 .

lst=[1,2,2,2,3,3,4,4,5,6]
from collections import Counter
Counter(lst).most_common(1)[0]

Counter(lst) returns a dict of element-occurence pairs. most_common(n) returns the n most common elements from the dict, along with the number of occurences.

You can use the hashmap/dict to get the most_common item (without importing any lib):

>>> l = [1, 2, 3, 4, 4, 4]
>>> counts = dict()
>>> # make a hashmap - dict()
>>> for n in nums:
    counts[n] = counts.get(n, 0) + 1
>>> most_common = max(counts, key=counts.get)
   4

You can get the unique values first:

l = [1, 2, 3, 4, 4, 4]
s = set(l)

then you can create list of (occurrences, value) tuples

freq = [(l.count(i), i) for i in s]  # [(1, 1), (1, 2), (1, 3), (3, 4)]

get the "biggest" element (biggest number of occurrences, the biggest value if there are more than one with the same number of occurrences):

result = max(freq)  # (3, 4)

and print the value:

print(result[1])  # 4

or as a "one-liner" way:

l = [1, 2, 3, 4, 4, 4]
print(max((l.count(i), i) for i in set(l))[1])  # 4

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