【问题标题】:Variables scope for nested python for-loop [duplicate]嵌套python for循环的变量范围[重复]
【发布时间】:2016-07-17 07:06:04
【问题描述】:

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

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']

【问题讨论】:

    标签: python variables for-loop scope nested


    【解决方案1】:

    代替:

    newi = i
    

    替换为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2017-07-29
      • 2011-07-10
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多