哪个更快? Counter()+=Counter
或 Counter.update(Counter)
?
为什么一个比另一个更快?
我尝试了一些简单的分析,但我认为这不足以最终证明 Counter+=Counter
比 Counter.update(Counter)
更快:
from collections import Counter
import time
x = Counter(['abc','def', 'abc'])
y = Counter(['xyz', 'xyz', 'uvw', 'abc'])
start = time.time()
x.update(y)
end = time.time() - start
print x
print 'update:', end
print
x = Counter(['abc','def', 'abc'])
start = time.time()
x+=y
end = time.time() - start
print x
print 'plus:', end
[输出]:
Counter({'abc': 3, 'xyz': 2, 'def': 1, 'uvw': 1})
update: 4.48226928711e-05
Counter({'abc': 3, 'xyz': 2, 'def': 1, 'uvw': 1})
plus: 2.28881835938e-05
最佳答案
Counter.update() 方法的设计速度更快。 __add__() 方法做了更多的工作,因为它必须消除非负值:
# heart of the update() loop in Python 2:
for elem, count in iterable.iteritems():
self[elem] = self_get(elem, 0) + count
# heart of the __add__() loop in Python 2:
result = Counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
如您所见,__add__ 方法做了更多的工作。
Python 3 的更高版本中还有另一个区别,它具有一个 __iadd__() 方法,该方法执行真正的就地更新,其工作量比 __add__() 少> 方法创建一个新计数器,然后进行赋值以替换旧计数器:
def __iadd__(self, other):
for elem, count in other.items():
self[elem] += count
return self._keep_positive()
关于python - Counter()+=Counter 和 Counter.update(Counter) 哪个更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443512/