简体   繁体   English

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

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

I have an input list, say x = [1,1,2,1,4,3,5,3,3] and I want to find the mode using Python 2.6. 我有一个输入列表,例如x = [1,1,2,1,4,3,5,3,3] ,我想使用Python 2.6查找模式。

Google so far gives me only answers such as Counter , statistics and mode() which all work for Python 2.7 and higher, but not 2.6. 到目前为止,Google仅给我提供了Counterstatisticsmode()答案,这些答案都适用于Python 2.7和更高版本,但不适用于2.6。

My question now is: would anyone know how to easily calculate the mode(s) of such a list without programming the whole function itself? 我现在的问题是:没有人知道如何在不编写整个函数本身的情况下轻松计算出这种列表的模式吗?

If you're doing statistical work, you might already have scipy installed. 如果您要进行统计工作,则可能已经安装了scipy If that's the case, you can use scipy.stats.mode . 如果是这样,您可以使用scipy.stats.mode

If not, you'll need to write your own function or get one from some other 3rd party library since there isn't one in the standard library in python2.6. 如果没有,您将需要编写自己的函数或从其他第三方库中获取一个,因为python2.6的标准库中没有该函数。

Also, apparently, scipy.stats.mode only depends on numpy , so you could just copy the source for that if you have numpy but don't want to download scipy . 另外,显然, scipy.stats.mode仅取决于numpy ,因此,如果您拥有numpy但不想下载scipy ,则可以仅复制源代码 . .

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

result: 结果:

[1, 3]

if you need to reuse, maybe a lambda function: 如果您需要重用,也许可以使用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)

If you're averse to writing your own function, check PyPI for possible modules. 如果您不想编写自己的函数,请检查PyPI可能的模块。 This one seems to be a likely candidate, but there may be others: 这个人似乎很可能是候选人,但可能还有其他人:

https://pypi.python.org/pypi/Counter/1.0.0 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)

result: 结果:

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

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

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