for循环不返回第一个forloop

时间:2015-08-16 23:22:15

标签: python for-loop dictionary scope copy

我遇到的问题是我的脚本返回到此程序中的第一个for循环,现在它只返回到第二个。我试图弄清楚如何通过所有步骤强制它。

提前致谢

import copy

test = {'AEP': {'days': [1]}, 'AES': {'days': [32]},'AIS': {'days': [7]},'TWO': {'days': [35]}}

print (test)
for stock in test:
    a = stock
    print ("step one")
    for stock in test.itervalues():
        print ("step two")
        for days in stock.itervalues():
            print ("step three")
            for i in days:
                print ("step four")
                if i <= 30:
                    days[days.index(i)] = i + 1
                else:
                    test_2 = copy.deepcopy(test)
                    test_2.pop(a)
                    print (str(a) + " Has been removed")
                    test = copy.deepcopy(test_2)

print (test)

当前流量/日志:

{'AEP': {'days': [1]}, 'AES': {'days': [32]}, 'TWO': {'days': [35]}, 'AIS': {'days': [7]}}
step one
step two
step three
step four
step two
step three
step four
AEP Has been removed
step two
step three
step four
Traceback (most recent call last):
  File "fortest.py", line 19, in <module>
    test_2.pop(a)

以下是我希望看到的最终结果

test = {'AEP': {'days': [1]},'AIS': {'days': [7]}} 

1 个答案:

答案 0 :(得分:0)

所以我继续将第一个for循环与第二个循环结合起来,这样变量仍然与它到达if和else语句的变量相同。

import copy

test = {'AEP': {'days': [1]}, 'AES': {'days': [32]},'AIS': {'days': [7]},'TWO': {'days': [35]}}


print (test)
for stock,stock_name in zip(test.itervalues(),test):
    a = stock_name
    print ('step one')
    for days in stock.itervalues():
        print ("step two")
        for i in days:
            print ("step three")
            if i <= 30:
                days[days.index(i)] = i + 1
            else:
                test_2 = copy.deepcopy(test)
                test_2.pop(a)
                print (str(a) + " Has been removed")
                test = copy.deepcopy(test_2)

print (test)

当前流量/日志:

{'AEP': {'days': [1]}, 'AES': {'days': [32]}, 'TWO': {'days': [35]}, 'AIS': {'days': [7]}}
step one
step two
step three
step one
step two
step three
AES Has been removed
step one
step two
step three
TWO Has been removed
step one
step two
step three
{'AEP': {'days': [2]}, 'AIS': {'days': [7]}}