计算Python列表中出现次数的最快方法

时间:2012-09-17 03:02:25

标签: python list repeat

我有一个Python列表,我想知道在这个列表中计算项目出现次数'1'的最快方法是什么。在我的实际情况中,该项目可能会发生数万次,这就是为什么我想要一个快速的方式。

['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']

collections模块有帮助吗?我正在使用Python 2.7

5 个答案:

答案 0 :(得分:68)

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

它可能在C级别上进行了大量优化。

编辑:我随机生成了一个大型列表。

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

修改编辑:可以使用collections.Counter

完成此操作
a = Counter(your_list)
print a['1']

在我上一个时间示例中使用相同的列表

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

我的时机过于简单化,并且取决于许多不同的因素,但它为您提供了良好的表现线索。

这是一些分析

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

答案 1 :(得分:12)

使用计数器字典以最有效的方式计算所有元素的出现次数以及python列表中最常见的元素及其出现值。

如果我们的python列表是: -

l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']

要查找python列表中每个项目的出现,请使用以下命令: -

\>>from collections import Counter

\>>c=Counter(l)

\>>print c

Counter({'1': 6, '2': 4, '7': 3, '10': 2})

要查找python列表中最多/最高出现的项目: -

\>>k=c.most_common()

\>>k

[('1', 6), ('2', 4), ('7', 3), ('10', 2)]

最高者: -

\>>k[0][1]

6

对于项目,只需使用k [0] [0]

\>>k[0][0]

'1'

对于第n个最高项目及其在列表中的出现次数,请使用以下内容: -

**,n = 2 **

\>>print k[n-1][0] # For item

2

\>>print k[n-1][1] # For value

4

答案 2 :(得分:0)

lambda和map函数的组合也可以完成这项工作:

list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2

答案 3 :(得分:0)

您可以使用pandas,方法是将list转换为pd.Series,然后只需使用.value_counts()

import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()

Input  >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)

答案 4 :(得分:-1)

您可以使用空格分隔的元素转换字符串中的列表,并根据要搜索的数字/字符将其拆分..

对于大型清单来说会干净而且快速。

>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3
相关问题