簡體   English   中英

如何找到沒有頻率的列表或元組的模式?

[英]How do I find the mode of a list or tuple without the frequency?

我正在嘗試查找元組中出現次數最多的數字,並將該值分配給變量。 我嘗試了以下代碼,但是當我只需要模式時,它為我提供了頻率和模式。

from collections import Counter
self.mode_counter = Counter(self.numbers)
self.mode = self.mode_counter.most_common(1)

print self.mode

有沒有一種方法可以使用Counter將模式分配給self.mode?

只需解壓縮most_common的返回值即可。

[(mode, _)] = mode_counter.most_common(1)

most_common(1)返回1個元組的列表。

您有兩種可能性:

使用self.mode, _ = self.mode_counter.most_common(1)[0]丟棄第二個值

使用self.mode = self.mode_counter.most_common(1)[0][0]僅獲取第一個值

暫無
暫無

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

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