这个问题在这里已有答案:
今天我发现,我无法复制清单。也不使用.copy()方法,也不使用切片。它总是指两个列表。
我通过列表理解创建相同的列表,但由于某些原因常见的方法不起作用。
你能解释为什么我的代码与copy()/切片无法正常工作吗?
注意:2个列表与内容不同但不应该重要,因为我的计划是根据程序后面写的条件更改它们的每个项目。
def find_next_gen(generation):
generation2 = [['.' for x in range(n)] for x in range(m)]
# generation2 = generation1[:] <- didn't work
# generation2 = generation1.copy() <- didn't work
for i, row in enumerate(generation1):
for j, element in enumerate(row):
# checking alive_neighbours:
alive_neighbours = 0
# same row:
alive_neighbours += check(generation1[i][j - 1] if j != 0 else generation1[i][-1])
alive_neighbours += check(generation1[i][j + 1] if j != n - 1 else generation1[i][0])
# row above:
if i == 0:
row_num_above = -1
else:
row_num_above = i - 1
alive_neighbours += check(generation1[row_num_above][j - 1] if j != 0 else generation1[row_num_above][-1])
alive_neighbours += check(generation1[row_num_above][j])
alive_neighbours += check(generation1[row_num_above][j + 1] if j != n - 1 else generation1[row_num_above][0])
# row beneath:
if i == m - 1:
row_num_beneath = 0
else:
row_num_beneath = i + 1
alive_neighbours += check(generation1[row_num_beneath][j - 1] if j != 0 else generation1[row_num_beneath][-1])
alive_neighbours += check(generation1[row_num_beneath][j])
alive_neighbours += check(generation1[row_num_beneath][j + 1] if j != n - 1 else generation1[row_num_beneath][0])
# create new generation:
if generation1[i][j] == 'X' and 3 >= alive_neighbours >= 2 or generation1[i][j] == '.' and alive_neighbours == 3:
generation2[i][j] = 'X'
else:
generation2[i][j] = '.'
return generation2
您需要copy.deepcopy()
来复制嵌套列表。否则,您将成功复制顶级列表,但新副本的元素仍将引用相同的子列表。