python - 如何在Python中完全复制列表?

标签 python

今天我注意到,我无法复制列表。也不使用 .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()来复制嵌套列表。否则,您将成功复制顶级列表,但新副本的元素仍将引用相同的子列表。

关于python - 如何在Python中完全复制列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091792/

相关文章:

python - 如何使 **kwargs 可选

python - 将 System.Double[] 转换为 Python

python - 以其他列组的最大值为条件计算新列

python - 如何将输出文件转换为数组

python - 值错误 : too many values to unpack (expected 2)

python - 如何防止 sqlalchemy 在 select 上创建事务?

python - 为什么 `in` 在 Series 包含字符串时不搜索值

python - 三次图和二次图?

python - 通过模型中的方法对 Django 模型进行排序

python - Django:openpyxl 将工作簿保存为附件