首页 > 解决方案 > 二维列表被覆盖

问题描述

import numpy as np

ulist = [] 

npts    = 10
maxiter = 4
x = np.linspace(1,10,npts)
x = x.tolist()

ulist.append(x)


i = 0
dt = 0.25

while i < maxiter:

    for j in range (npts):
        x[j] = x[j] - dt

    ulist.append(x)

    print('Values of x: ')
    print(x)
    print('Values of ulist: ')
    print(ulist[i][:])
    print()
    print()

    i += 1


print('------------This is after the while loop---------')
print('Values of x: ')
print(x)
for i in range(maxiter):
    print('Values of ulist: ')
    print(ulist[i][:])
    print()
    print()

在上面用python编写的代码中,我想修改列表'x'并继续将其附加到二维列表'ulist'中。当我在 while 循环中打印 x 和 ulist[i][:] 时,我得到的都是一样的。但是当我尝试在while循环之外打印它时,x的最后一个条目被复制到ulist中的所有列表中。我不知道发生了什么。有人可以解释一下吗?

标签: pythonlist

解决方案


推荐阅读