我遇到了一个问题,我需要列出一个列表,例如l = [1,2,3,4],成为一个例子,例如{1:1,2:1,3:1,4:1}。我只是想知道是否应该使用collections.Counter()或者只是自己编写一个循环来执行此操作。内置方法比自己编写循环更快吗?
答案 0 :(得分:4)
使用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个元素。
答案 1 :(得分:1)
取决于可读性 v / s 效率。让我们先看看两个实现。我将使用它作为样本运行的列表:
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()
的速度是自己代码的两倍。