python更改函数体中的循环变量

时间:2018-04-05 13:31:48

标签: python

我在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 ++不同。我的问题是,如果有人需要更改函数体内的循环索引,那怎么可能呢?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

你使用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