如何找到没有频率的列表或元组的模式?

2024-04-27 05:11:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到元组中出现最多的数字,并将该值赋给变量。我尝试了下面的代码,但它给了我频率和模式,当我只需要模式。在

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

print self.mode

有没有办法把模式分配给自我模式使用计数器?在


Tags: 代码fromimportselfmostmodecounter模式
2条回答

most_common(1)返回1元组的列表。在

你有两种可能:

使用 self.mode, _ = self.mode_counter.most_common(1)[0]放弃第二个值

使用self.mode = self.mode_counter.most_common(1)[0][0]只获取第一个值

只需解压缩most_common的返回值。在

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

相关问题 更多 >