gpt4 book ai didi

python - 在 python 中沿着列表复制元素

转载 作者:行者123 更新时间:2023-11-28 19:50:08 25 4
gpt4 key购买 nike

我有一个名为 hab 的列表列表,用作二维数组。在这个列表列表中,我存储了一个名为 loc 的类的元素,这就是为什么我不使用 numpy 数组(它不存储数字)的原因。

我想通过遍历每个元素,用随机选择的“loc”填充每个元素。但是,似乎每当我到达一行的末尾时,程序都会获取最后一行元素并将其放入该行的所有其他元素中。这意味着我最终得到的列表列表如下所示:

3 3 3 3 3  
1 1 1 1 1
2 2 2 2 2
2 2 2 2 2
4 4 4 4 4

实际上我希望所有这些数字都是随机的(这是打印出每个 loc 的特定特征,这就是为什么它是数字)。

这里是相关的代码:

allspec=[] # a list of species
for i in range(0,initialspec):
allspec.append(species(i)) # make a new species with new index
print 'index is',allspec[i].ind, 'pref is', allspec[i].pref
hab=[[0]*xaxis]*yaxis
respect = randint(0,len(allspec)-1)
for j in range(0,yaxis):
for k in range (0,xaxis):
respect=randint(0,len(allspec)-1)
print 'new species added at ',k,j,' is ', allspec[respect].ind
hab[k][j]=loc(k,j,random.random(),allspec[respect])
print 'to confirm, this is ', hab[k][j].spec.ind

for k in range (0,xaxis):
print hab[k][j].spec.ind

printgrid(hab,xaxis,yaxis)
print 'element at 1,1', hab[1][1].spec.ind

在循环中,我确认我创建的元素是我想要的元素,行 print 'to confirm, this is ', hab[k][j].spec.ind 现在没问题了。只有当该循环退出时,它才会以某种方式用相同的东西填充行中的每个元素。我不明白!

最佳答案

问题出在这里:

hab=[[0]*xaxis]*yaxis

作为上述语句的结果,habyaxis 引用到同一列表组成:

In [6]: map(id, hab)
Out[6]: [18662824, 18662824, 18662824]

当您修改 hab[k][j] 时,所有其他 hab[][j] 也会更改:

In [10]: hab
Out[10]: [[0, 0], [0, 0], [0, 0]]

In [11]: hab[0][0] = 42

In [12]: hab
Out[12]: [[42, 0], [42, 0], [42, 0]]

要修复,使用

hab=[[0]*xaxis for _ in range(yaxis)]

现在 hab 的每个条目都引用一个单独的列表:

In [8]: map(id, hab)
Out[8]: [18883528, 18882888, 18883448]

In [14]: hab
Out[14]: [[0, 0], [0, 0], [0, 0]]

In [15]: hab[0][0] = 42

In [16]: hab
Out[16]: [[42, 0], [0, 0], [0, 0]]

关于python - 在 python 中沿着列表复制元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13802572/

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