简体   繁体   English

选择列表的随机模式

[英]Choosing random mode of list

I have data that I would like to summarize by the mode of a list. 我有一些数据想通过列表的方式进行总结。 When there is more than one mode, I would like to choose from the modes randomly. 当有多个模式时,我想从这些模式中随机选择。 As I understand them, in a list with multiple modes the scipy and statistics mode functions return the first mode and raise an exception, respectively. 据我了解,在具有多个模式的列表中,scipy和statistics模式函数分别返回第一个模式并引发异常。 I've rolled my own function (as follows), but I'm wondering if there's a better way. 我已经发布了自己的函数(如下所示),但是我想知道是否有更好的方法。

import random

def get_mode(l):
    s = set(l)
    max_count = max([l.count(x) for x in s])
    modes = [x for x in s if l.count(x) == max_count]
    return random.choice(modes)

You can use Counter to do this: 您可以使用Counter来执行此操作:

from collections import Counter
from random import choice


def get_mode(l):
    c = Counter(l)
    max_count = max(c.values())
    return choice([k for k in c if c[k] == max_count])

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

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