2016-02-12 102 views
0

我有我想通过列表的模式来总结的数据。当有多种模式时,我想随机选择模式。据我了解,在具有多种模式的列表中,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) 

回答

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])