我偶尔会使用"技巧"通过映射版本扩展列表,例如有效地计算2的幂:
from operator import mul
powers = [1]
powers += map(mul, [2] * 10, powers)
print(powers) # prints [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
这取决于+=
会立即将map
中的每个值追加到列表中,这样map
就会找到它,过程就会继续.换句话说,它需要这样工作:
powers = [1]
for value in map(mul, [2] * 10, powers):
powers.append(value)
而不是像这样首先计算并存储整个右手边,其中powers
最后是[1, 2]
:
powers = [1]
powers += list(map(mul, [2] * 10, powers))
是否有地方保证它能像它一样工作?我查看了Mutable Sequence Types个文档,但除了暗示s += t
和s.extend(t)
是等价的之外,它没有说太多.它指的是MutableSequence
,其source code包括:
def extend(self, values):
'S.extend(iterable) -- extend sequence by appending elements from the iterable'
if values is self:
values = list(values)
for v in values:
self.append(v)
def __iadd__(self, values):
self.extend(values)
return self
这确实表明,它确实需要supposed个,才能像我所希望的那样工作,但是一些源代码并不像文档中的保证那样安全.