在for for循环内定义的增量变量不会影响循环的outter

时间:2017-02-19 15:06:35

标签: python algorithm

In [6]: for i in range(0, 3):
    print(i)
    for k, v in test.items():
        hee = 5
        if key == 'test1':
            hee = hee + 5
            print(hee)
   ...:
0
10
10
1
10
10
2
10
10

我希望结果如下:

0
10
10
1
15
15
2
20
20

有没有办法使用类似的代码获得此输出:两个for循环但内部for循环有变量,每次都会增加,而不管外循环?

1 个答案:

答案 0 :(得分:0)

下面的代码应该可以胜任。我已添加评论以供解释。

test = {'sna':[10,20,30], 'dna':[100,200,300]}

# create a temporary variable to store initial value of hee which is 5
temp = 5
for i in range(0, 3):
    print(i)
    for k, v in test.items():
        # set hee to temp
        hee = temp
        if k == 'sna':
            hee = hee + 5
            temp = hee
            print(hee)
            print(hee)
            # you might want to use break statement since each key is unique in dictionary
            # once you find key, there is no need to iterate through the dictionary
            break

输出:

0
10
10
1
15
15
2
20
20