簡體   English   中英

python更改函數體中的循環變量

[英]python change the loop variable in function body

我發現Python中的行為有點違反直覺(或者不是我慣用的行為!)。 因此,我有一些代碼如下:

for c in range(10):
    c += 1
    print(c)

此打印

1
2
3
4
5
6
7
8
9
10

甚至做類似的事情:

c = 0
for c in range(10):
   ...

不更改輸出? 我想范圍規則與C ++不同。 我的問題是,是否有人需要更改函數體內的循環索引,怎么辦?

for語句是一種賦值形式; 執行主體后,將為c分配一個新值,覆蓋您可能對主體所做的任何更改。 也就是說,循環

for c in range(10):
    c += 1
    print(c)

相當於

itr = iter(range(10))
while True:
    try:
        c = next(itr)
    except StopIteration:
        break
    c += 1
    print(c)

如果要修改c ,則需要使用while循環:

c = 0
while c < 10:
    ...  # Arbitrary code, including additional modifications of c
    c += 1  # Unconditionally increase c to guarantee the loop eventually ends

無法使用for循環在Python中更改循環索引 如chepner在其回答中所述,它將重設每個循環。

但是,您可以使用一個步驟(范圍的第三個變量)來編寫它。 要插入步驟,您也需要通過開始和結束。

for c in range(1,10,2): # start, end (not included), step
    print(c)

# 1,3,5,7,9

for c in range(9,0,-2): 
    print(c)

# 9,7,5,3,1

暫無
暫無

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

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