[英]Doubley unpacking an iterable in Python 3 removes the iterable?
lst = iter([1, 2, 3])
print([*lst]) # >>> [1, 2, 3]
print([*lst]) # >>> []
這是解壓縮的預期行為嗎? 我會假設原始數據在解包時不會被修改而且只是制作副本?
編輯:
如果是這樣,背后的原因是什么?
是的,這是解壓縮迭代器的預期行為:
>>> lst = [1, 2, 3]
>>> iter(lst)
<list_iterator at 0x7fffe8b84ef0>
迭代器只能迭代一次然后就會耗盡。
>>> i = iter(lst)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-11-a883b34d6d8a> in <module>()
----> 1 next(i)
StopIteration:
迭代器協議指定耗盡的迭代器必須在其__next__
方法的后續調用中繼續引發StopIteration
異常。 因此,再次迭代它是有效的(不是錯誤),但迭代器不應該產生新項:
>>> list(i)
[]
沒有什么能阻止你定義一個違反這個規則的迭代器,但是這樣的迭代器被認為是“壞了” 。
但是, 可迭代列表可以多次解壓縮。
>>> lst = [1, 2, 3]
>>> print(*lst)
1 2 3
>>> print(*lst)
1 2 3
您可以根據需要從同一源列表創建任意數量的獨立迭代器:
>>> i1 = iter(lst)
>>> i2 = iter(lst)
>>> next(i2)
1
>>> next(i2)
2
>>> next(i1) # note: it's another 1
1
你混淆了“迭代器”和“迭代”的術語。
迭代器(通常)不能再次迭代。 另一方面, 可迭代 (如列表)可以:
lst = [1, 2, 3]
print([*lst]) # >>> [1, 2, 3]
print([*lst]) # >>> [1, 2, 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.