如何在python中生成多维列表

2024-04-19 20:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试根据两个变量生成多维列表:sizedim。它们都是用用户输入初始化的,所以我在编码时不知道它们的值。有dim = 3size = 2的例子是:[[['+', '+'], ['+', '+']], [['+', '+'], ['+', '+']]]。到目前为止,我尝试了:

import copy
fields = '+'
for i in range(dim):
    fields = [copy.copy(fields) for j in range(size)]

虽然这种方法对于dim in [1, 2]非常有效,但它只在dim > 2时创建对同一列表的引用。以size = 3dim = 3为例:

>>> f
[[['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]]
>>> f[0][0][0] = 'X'
>>> f
[[['X', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['X', '+', '+'], ['+', '+', '+'], ['+', '+', '+']], [['X', '+', '+'], ['+', '+', '+'], ['+', '+', '+']]]

我从像f = [[['+'] * 3] * 3] * 3这样的代码中知道这种行为,并认为我可以用copy.copy()来防止这种行为,但这显然行不通。我用android上的Python3.2.2(Qpython3)和Windows上的Python2.7尝试了这个方法,得到了相同的结果。请注意,我不想使用像numpy这样的非标准库。你知道吗


Tags: 方法代码用户inimport编码fields列表
2条回答

你可以用复制.deepcopy(). 这个复制。复制()是肤浅的。你知道吗

这两种方法的区别:

the difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

为此,我将使用numpy数组来提供更方便的切片和索引操作。也允许更多的尺寸比2-3和更干净的代码。你知道吗

import numpy as np
X = np.empty((width, height), dtype=object)

然后您可以通过所需的方法进行填充,例如:

import itertools
for x, y in itertools.product(range(width), range(height)):
     X[x, y] = '+'

相关问题 更多 >