在 Python 2.6 中是否有任何函数可以找到列表的模式(如果最多出现超过 1 个值,则为多个)?

Is there any function to find the mode (or multiple if more than 1 value occurs most) of a list in Python 2.6?

我有一个输入列表,比如 x = [1,1,2,1,4,3,5,3,3],我想使用 Python 2.6 查找模式。

Google 到目前为止只给我答案,例如 Counterstatisticsmode(),它们都适用于 Python 2.7 及更高版本,但不适用于2.6.

我现在的问题是:有人知道如何在不对整个函数本身进行编程的情况下轻松计算此类列表的模式吗?

如果您不想编写自己的函数,请检查 PyPI 以获取可能的模块。这个似乎是一个可能的候选人,但可能还有其他人:

https://pypi.python.org/pypi/Counter/1.0.0

x= [1,2,3,1,2,4,5]
y = set(x)
countDict = {}
for item in y:
    countDict[item] = x.count(item)

结果:

{1: 2, 2: 2, 3: 1, 4: 1, 5: 1}

如果您正在做统计工作,您可能已经安装了scipy。如果是这样,您可以使用 scipy.stats.mode.

如果没有,您需要编写自己的函数或从其他第三方库中获取一个函数,因为 python2.6.

中的标准库中没有

另外,显然,scipy.stats.mode 只依赖于 numpy,所以如果你有 numpy 但不想下载 copy the source =10=]。 . .

x = [1,1,2,1,4,3,5,3,3]
print [i for i in set(x) if x.count(i) == max(map(x.count, x))]

结果:

[1, 3]

如果您需要重用,可能是 lambda 函数:

mode = lambda x: [i for i in set(x) if x.count(i) == max(map(x.count, x))]
x = [1,1,2,1,4,3,5,3,3]
print mode(x)