[英]Change list, that you are iterating through, in that loop
就我而言,我有一個for循環,遍歷一個列表,但是我想在上述循環中更改該列表。 之后,我希望for循環遍歷新列表。
li = [4,5,6,7,8,9]
for item in li:
#do something
if item == 5:
#now continue iterating through this loop and not the old one
li = [9,9,9,9,9,9]
我該怎么做?
盡管@BoarGules的評論是正確的,但您可以使用枚舉解決問題。
li = [4,5,6,7,8,9]
for i, item in enumerate(li):
print(li[i])
if li[i] == 5:
li = [9,9,9,9,9,9]
輸出:
>4
>5
>9
>9
>9
您不應該通過迭代來更改列表。 我會使用索引:
for i in range(len(li)):
if li[i] == 5:
li = len(li) * [9]
要了解為什么這行不通, for
循環等效於while
循環,如下所示:
# for x in y:
# ...
itr = iter(y)
while True:
try:
x = next(itr)
except StopIteration:
break
...
如果為y
分配新的內容,則該循環不會受到影響,因為它僅在分配給y
的原始值(而不是名稱y
本身)上使用迭代器。
但是,如果您確實在循環體內更改了列表,則迭代器可能會返回您不期望的值。 如果需要更改迭代器,最好自己獲取迭代器。
li = [4,5,6,7,8,9]
itr = iter(li)
while True:
try:
item = next(itr)
except StopIteration:
break
#do something
if item == 5:
#now continue iterating through this loop and not the old one
itr = iter([9,9,9,9,9])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.