繁体   English   中英

Python collections.Counter()运行时

[英]Python collections.Counter() runtime

我只是遇到一个问题,我需要将一个列表(例如l = [1、2、3、4])放入一个dic,例如{1:1、2:1、3:1、4:1}。 我只想知道是应该使用collections.Counter()还是自己编写一个循环来执行此操作。 内置方法比自己编写循环快吗?

您始终可以使用timeit模块测试是否更快。 在Python 3中, Counter对象提高了C性能,并且确实非常快:

>>> from timeit import timeit
>>> import random, string
>>> from collections import Counter, defaultdict
>>> def count_manually(it):
...     res = defaultdict(int)
...     for el in it:
...         res[el] += 1
...     return res
...
>>> test_data = [random.choice(string.printable) for _ in range(10000)]
>>> timeit('count_manually(test_data)', 'from __main__ import test_data, count_manually', number=2000)
1.4321454349992564

>>> timeit('Counter(test_data)', 'from __main__ import test_data, Counter', number=2000)
0.776072466003825

这里Counter()快了2倍。

就是说,除非您在代码的性能关键部分中进行计数,否则请着重于可读性和可维护性,在这方面, Counter()胜过您自己编写的代码。

除此之外, Counter()对象还提供了词典基础上的功能:它们可以被视为多集 (您可以对计数器进行加或减,并产生并集或交集),并且它们可以有效地按计数为您提供前N个元素。

这取决于可读性效率 让我们先看看两个实现。 我将使用它作为示例运行的列表:

my_list = [1, 2, 3, 4, 4, 5, 4, 3, 2]

使用collections.Counter()

from collections import Counter
d = Counter(my_list)

使用collections.defaultdict()创建我自己的计数器:

from collections import defaultdict
d = defaultdict(int)
for i in [1, 2, 3, 4, 4, 5, 4, 3, 2]: 
    d[i] += 1

如您所见, collections.Counter()更具可读性

让我们看看使用timeit效率:

  • Python 2.7中

     mquadri$ python -m "timeit" -c "from collections import defaultdict" "d=defaultdict(int)" "for i in [1, 2, 3, 4, 4, 5, 4, 3, 2]: d[i] += 1" 100000 loops, best of 3: 2.95 usec per loop mquadri$ python -m "timeit" -c "from collections import Counter" "Counter([1, 2, 3, 4, 4, 5, 4, 3, 2])" 100000 loops, best of 3: 6.5 usec per loop 

    collection.Counter()实现比自己的代码慢2倍

  • Python 3中

     mquadri$ python3 -m "timeit" -c "from collections import defaultdict" "d=defaultdict(int)" "for i in [1, 2, 3, 4, 4, 5, 4, 3, 2]: d[i] += 1" 100000 loops, best of 3: 3.1 usec per loop mquadri$ python3 -m "timeit" -c "from collections import Counter" "Counter([1, 2, 3, 4, 4, 5, 4, 3, 2])" 100000 loops, best of 3: 5.57 usec per loop 

    collections.Counter()速度是自己代码的两倍

暂无
暂无

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

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