python while循环没有显示正确的输出?

时间:2018-03-20 20:44:12

标签: python

这很奇怪,我很确定代码在没有while循环的情况下工作:

target = [[1],]
add = [2,4]
count = 0

while count < 2:
    temp = []
    for i in target:
        temp += [i, i]
    target = temp[:]

    print('before', target)

    idx = 0
    while idx < len(target):
        target[idx].append(add[idx])
        idx += 1

    print('after', target)        

    add += add      
    count += 1

这里我有target作为包含数字的嵌套列表,我有add就像一个数字列表。我的想法是将target每个循环加倍,然后将add中的一个项添加到target的一个子列表中,然后将add加倍。

我得到了结果:

before [[1], [1]]
after  [[1, 2, 4], [1, 2, 4]]
before [[1, 2, 4], [1, 2, 4], [1, 2, 4], [1, 2, 4]]
after  [[1, 2, 4, 2, 4, 2, 4], [1, 2, 4, 2, 4, 2, 4], [1, 2, 4, 2, 4, 2, 4], [1, 2, 4, 2, 4, 2, 4]]

如果您查看之前和之后,整个add已添加到target的每个子列表中,而不是将add[0]添加到target[0],然后{ {1}}至add[1]以下显示为我的期望:

target[1]

没有外部while循环:

before [[1], [1]]
after  [[1, 2], [1, 4]]
before [[1, 2], [1, 4], [1, 2], [1, 4]]
after  [[1, 2, 2], [1, 4, 4], [1, 2, 2], [1, 4, 4]]

无法理解为什么

1 个答案:

答案 0 :(得分:2)

问题在于这段代码:

temp = []
for i in target:
    temp += [i, i]
target = temp[:]

当它循环遍历target时,它会拉出每个项目,在这种情况下是一个列表([1])。然后将此特定列表(不是副本)添加两次到temp列表。你需要做的是在构建temp时复制:

temp = []
for i in target:
    temp += [i[:], i[:]]
target = temp
相关问题