簡體   English   中英

Python:獲取列表中最低、最頻繁的值

[英]Python: Get the lowest, most frequent value of a list

嗨社區? 你能幫我解決以下問題嗎? 我無法為我的問題找到有效的解決方案。 非常感謝任何幫助! 提前感謝大家!

我的問題:作為第一步,我想確定給定整數列表中最常見的值。 作為第二步,如果有多個最常見的值,我想取其中最低的一個。

示例:給定以下列表,我想收到“ 5 ”,因為它是最低、最頻繁的值。

list = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]

請你幫助我好嗎? 謝謝!

In [24]: list = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
    ...:

In [25]: max(sorted(set(list)), key=list.count)
Out[25]: 5

可以使用內置Counter class 在線性時間內從多個候選值中獲取最常見的值:

from collections import Counter

l = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
counter = Counter(l)
_, top_freq = counter.most_common(1)[0]
lower_most_common = min(key for key, freq in counter.items() if freq == top_freq)

暫無
暫無

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

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