簡體   English   中英

找到最常見的元素

[英]Find most common element

如何在不導入庫的情況下打印列表中最常見的元素?

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

所以我希望 output 是4

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

Counter(lst)返回元素出現對的dict most_common(n)從字典中返回 n 個最常見的元素,以及出現的次數。

您可以使用 hashmap/dict 獲取 most_common 項(無需導入任何庫):

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

您可以先獲取唯一值:

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

然后您可以創建(出現次數,值)元組列表

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

獲取“最大”元素(出現次數最多,如果有多個相同的出現次數,則為最大值):

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

並打印值:

print(result[1])  # 4

或作為“單線”方式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM