簡體   English   中英

Python:如何在 2 個 for 循環中交換 2 個迭代器的值?

[英]Python: how to swap values of 2 iterators in 2 for loops?

我有一個想要這樣運行的代碼:

for i in range(10):
    for j in range(10):

    if a condition is satisfied:
    let i = j in the next loop, j is reset back to 0

示例:如果i = 0, j = 0且條件不滿足 => 繼續
如果i = 0, j = 1並且條件滿足 => 讓i = j
下一個循環: i = 1, j = 0然后i = 1, j = 1並且循環繼續。

更多示例:如果i = 3, j = 2並且滿足條件:下一個循環: i = 2, j = 3

在下一次 for 循環迭代中無法更改i 您必須使用 while 循環:

i,j = 0,0
while i < 10:
    while j < 10:

    if a condition is satisfied:
    let i = j in the next loop, j is reset back to 0

您不能使用range()因為它會產生一個生成器,它不關心ij的當前(編輯)值。

你可以用一個while循環來做你想做的事情。

i = 0
j = 0
while(i < 10):
    j = 0
    while(j < 10):
        if condition:
            i, j = j, i
        j += 1
    i += 1

嘗試使用while

i, j = 0, 0
while i < 10:
    while j < 10:
        if a condition is satisfied:
            i, j = j, i
        j += 1
    i += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM