在内部for循环中定义的增量变量不受外部for循环的影响

2024-04-26 18:51:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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循环有一个变量,不管外部循环是什么,每次都递增?你知道吗


Tags: 方法key代码intestforifitems
1条回答
网友
1楼 · 发布于 2024-04-26 18:51:55

下面的代码应该做的工作。我补充了一些解释。你知道吗

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

相关问题 更多 >