Python通过嵌套列表传递值?

时间:2017-11-17 03:02:18

标签: python

我有一个让我感到沮丧的简单问题。我确定我犯了一个非常明显的错误,但我似乎无法找到它。在进行迭代之前,我希望l成为import random def runtest(n,steps): l=[] for i in range(n): sublist=[] for j in range(n): sublist.append(0) l.append(sublist) for k in range(n-1): i = random.randint(0,n-1) j = random.randint(0,n-1) while(l[i][j]==1): i = random.randint(0,n-1) j = random.randint(0,n-1) l[i][j]=1 l_old = list(l) print("L_OLD BEFORE ITERATION", l_old) for k in range(steps): for i in range(n): for j in range(n): num = 0 if i is not 0: num+=l[i-1][j] if i is not n-1: num+=l[i+1][j] if j is not 0: num+=l[i][j-1] if j is not n-1: num+=l[i][j+1] if(num > 1): l[i][j]=1 print("L_OLD AFTER ITERATION",l_old) return sum([sum(item) for item in l]), l_old, l 的副本。我有以下Python脚本。

BEFORE ITERATION [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
AFTER ITERATION: [[0, 0, 0, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]

但是,我的输出将如下所示:

l

即使我复制了l的值而不是l[:]的引用,它也在变化。我尝试了(tensorflow)$ pip install --upgrade pip # for Python 2.7 (tensorflow)$ pip3 install --upgrade pip # for Python 3.n (tensorflow)$ pip install --upgrade tensorflow # for Python 2.7 (tensorflow)$ pip3 install --upgrade tensorflow # for Python 3.n (tensorflow)$ pip install --upgrade tensorflow-gpu # for Python 2.7 and GPU (tensorflow)$ pip3 install --upgrade tensorflow-gpu # for Python 3.n and GPU (tensorflow)$ pip install --upgrade tensorflow-gpu==1.4.1 # for a specific version 同样的结果。我错过了什么?我认为这与它是一个嵌套列表的事实有关,但我如何编写它以便所有嵌套列表都按值复制?

1 个答案:

答案 0 :(得分:2)

  

我认为这与它是一个嵌套列表的事实有关,

是。你做了一个浅薄的副本:

l_old = list(l)

使用l[:]进行切片也是一个浅层副本。

  

但是如何编写它以便所有嵌套列表都按值复制?

尝试深层复制:

from copy import deepcopy
l_old = deepcopy(l)