我偶爾會使用“技巧”通過自身的映射版本來擴展串列,例如有效地計算 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 Typess = t檔案,但除了暗示and等價之外,它并沒有說太多s.extend(t)。它確實參考了MutableSequence,其源代碼包括:
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
這確實表明它確實應該像我想要的那樣作業,但是某些源代碼就是它的樣子,感覺不像檔案中的保證那樣安全。
uj5u.com熱心網友回復:
我沒有看到任何保證貪婪行為的測驗或檔案;但是,我確實認為這是預期的行為,并且野外的代碼依賴于它。
FWIW, =串列相當于list.extend(),所以你的“技巧”歸結為:
>>> powers = [1]
>>> powers.extend(2*x for x in islice(powers, 10))
>>> powers
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
雖然我還沒有找到 =or的保證extend,但我們確實保證串列迭代器在迭代時允許突變。1因此,這段代碼是有根據的:
>>> powers = [1]
>>> for x in powers:
if len(powers) == 10:
break
powers.append(2 * x)
>>> powers
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
1 請參閱表格后面的第二段: https ://docs.python.org/3/library/stdtypes.html#common-sequence-operations :
可變序列上的正向和反向迭代器使用索引訪問值。即使基礎序列發生突變,該索引也將繼續向前(或向后)前進。迭代器僅在遇到 IndexError 或 StopIteration 時(或索引降至零以下)終止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471069.html
上一篇:在串列串列中插入一個值
