简体   繁体   English

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

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

I'm trying to find the most occurring number in a tuple and assign that value to a variable. 我正在尝试查找元组中出现次数最多的数字,并将该值分配给变量。 I tried the following code, but it gives me the frequency and the mode, when I only need the mode. 我尝试了以下代码,但是当我只需要模式时,它为我提供了频率和模式。

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

print self.mode

Is there a way to just assign the mode to self.mode using Counter? 有没有一种方法可以使用Counter将模式分配给self.mode?

只需解压缩most_common的返回值即可。

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

most_common(1) returns a list of 1 tuple. most_common(1)返回1个元组的列表。

You have two possibilities: 您有两种可能性:

Use self.mode, _ = self.mode_counter.most_common(1)[0] to discard the second value 使用self.mode, _ = self.mode_counter.most_common(1)[0]丢弃第二个值

Use self.mode = self.mode_counter.most_common(1)[0][0] to only get the first value 使用self.mode = self.mode_counter.most_common(1)[0][0]仅获取第一个值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM