嵌套python for-loop的变量范围

时间:2016-07-17 07:06:05

标签: python variables for-loop scope nested

我有两个嵌套的for循环和两个列表,我希望在内循环的一次迭代之后重新初始化一个列表。

def test():
i = ['1','5','9','3','6','4']
for x in xrange(0,len(i)):
    j = ['6', '7', '9', '3']
    newi = i
    for y in xrange(0,len(j)):
        newi[x] = j[y]
        print "i", i
    print "end of one iteration on finner loop"
    print "newi", newi
test()

它是一个虚拟代码,我希望在内循环的一次迭代后,newi的一个干净的新实例成为i的实例,目前它保留了内循环的值

当前输出:

i ['6', '5', '9', '3', '6', '4']
i ['7', '5', '9', '3', '6', '4']
i ['9', '5', '9', '3', '6', '4']
i ['3', '5', '9', '3', '6', '4']
end of one iteration on inner loop
newi ['3', '5', '9', '3', '6', '4']
i ['3', '6', '9', '3', '6', '4']
i ['3', '7', '9', '3', '6', '4']
i ['3', '9', '9', '3', '6', '4']
i ['3', '3', '9', '3', '6', '4']
end of one iteration on inner loop
newi ['3', '3', '9', '3', '6', '4']
i ['3', '3', '6', '3', '6', '4']
i ['3', '3', '7', '3', '6', '4']
i ['3', '3', '9', '3', '6', '4']
i ['3', '3', '3', '3', '6', '4']
end of one iteration on inner loop
newi ['3', '3', '3', '3', '6', '4']
i ['3', '3', '3', '6', '6', '4']
i ['3', '3', '3', '7', '6', '4']
i ['3', '3', '3', '9', '6', '4']
i ['3', '3', '3', '3', '6', '4']
end of one iteration on inner loop
newi ['3', '3', '3', '3', '6', '4']
i ['3', '3', '3', '3', '6', '4']
i ['3', '3', '3', '3', '7', '4']
i ['3', '3', '3', '3', '9', '4']
i ['3', '3', '3', '3', '3', '4']
end of one iteration on inner loop
newi ['3', '3', '3', '3', '3', '4']
i ['3', '3', '3', '3', '3', '6']
i ['3', '3', '3', '3', '3', '7']
i ['3', '3', '3', '3', '3', '9']
i ['3', '3', '3', '3', '3', '3']
end of one iteration on inner loop
newi ['3', '3', '3', '3', '3', '3']

1 个答案:

答案 0 :(得分:0)

而不是:

newi = i

替换为:

newi = list(i) # list(i) creates another copy  i