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

时间:2014-01-10 15:04:30

标签: python collections counter mode

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

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

print self.mode

有没有办法只使用Counter将模式分配给self.mode?

2 个答案:

答案 0 :(得分:4)

只需解压缩most_common的返回值。

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

答案 1 :(得分:2)

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

您有两种可能性:

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

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