我正在尝试在元组中找到最多的数字,并将该值分配给变量。我尝试了下面的代码,但它给了我频率和模式,当我只需要模式时。
from collections import Counter
self.mode_counter = Counter(self.numbers)
self.mode = self.mode_counter.most_common(1)
print self.mode
有没有办法只使用Counter将模式分配给self.mode?
答案 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]
仅获取第一个值