gpt4 book ai didi

Python 使用嵌套列表传递值?

转载 作者:行者123 更新时间:2023-12-01 02:26:23 24 4
gpt4 key购买 nike

我遇到了一个令我沮丧的简单问题。我确信我犯了一个非常明显的错误,但我似乎找不到它。我希望 l_old 在进行迭代之前成为 l 的副本。我有以下 Python 脚本。

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

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

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[:] 得到了相同的结果。我缺少什么?我认为这与它是一个嵌套列表这一事实有关,但是我该如何编写它以便所有嵌套列表都按值复制?

最佳答案

I think it has to do with the fact that it's a nested list,

是的。您已经完成了浅复制:

l_old = list(l)

使用l[:]进行切片也是浅拷贝。

but how can I write it such that all nested lists are copied by value?

尝试深层复制:

from copy import deepcopy
l_old = deepcopy(l)

关于Python 使用嵌套列表传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47342613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com