【问题标题】:Choosing random mode of list选择列表的随机模式
【发布时间】:2016-02-12 19:09:48
【问题描述】:

我有想通过列表模式汇总的数据。当有多个模式时,我想从模式中随机选择。据我了解,在具有多种模式的列表中,scipy 和统计模式函数分别返回第一种模式并引发异常。我已经推出了自己的功能(如下),但我想知道是否有更好的方法。

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)

【问题讨论】:

    标签: python python-3.x random statistics


    【解决方案1】:

    您可以使用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])
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多