如何创建一个有3列和每列1000行的3D矩阵

-4 投票
3 回答
2281 浏览
提问于 2025-04-16 19:55

这是我写的代码:

positionMatrix = ([0]*1000, [0]*1000, [0]*1000)

3 个回答

-1

这段代码的意思是创建一个三维的矩阵,叫做 positionMatrix。这个矩阵的大小是 1000x1000x1000,也就是说它有一千层,每层有一千行,每行有一千列。每个位置的初始值都是 0。

在 C 或 C++ 语言中,这样的矩阵可以用 int positionMatrix[1000][1000][1000] 来表示。

0

如果性能不是特别重要,你可以在Python中用字典来当作多维数组。

positionMatrix = {}
positionMatrix[ row, col ] = foo

要把它初始化为3行1000列的零:

for col in range( 3 ):
    for row in range( 1000 ):
        positionMatrix[ row, col ] = 0.0

或者直接这样做:

from collections import defaultdict
positionMatrix = defaultdict(float)

这样在第一次访问每个元素时,它会自动初始化为0。

如果你需要高性能的数字矩阵,可以看看numpy这个库。

编辑:更新为3列1000行,而不是三维矩阵。

2

你想要的内容还不是很清楚。

如果你想要多维数组,可以使用列表:

>>> matrix = [[None]*10 for x in range(3)]#replace 10 with 1000 or what ever
>>> matrix
[[None, None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None, None]]
>>>

我还建议使用 None 而不是 0

你可以这样访问这个矩阵:

>>> matrix[1][3] = 55
>>> matrix
[[None, None, None, None, None, None, None, None, None, None], [None, None, None, 55, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None, None]]

这就是你想要的效果吗?

为了更好地展示,你可以这样做:

>>> for x in matrix:
...     print(x, "\n")
... 
[None, None, None, None, None, None, None, None, None, None] 

[None, None, None, 55, None, None, None, None, None, None] 

[None, None, None, None, None, None, None, None, None, None] 

你也可以选择:

>>> matrix = [[None]*10 for x in xrange(3)]

你可以在 这里 了解更多。

因为你使用的是 Python 3.x,所以应该使用 range()。更多信息请见 这里

哦,顺便说一下,你现在做的事情没有什么特别错误的地方,你使用的是元组而不是列表,元组是不可变的,但里面的嵌套列表是可以改变的,所以你可以修改它:

>>> positionMatrix = ([0]*10, [0]*10, [0]*10)
>>> positionMatrix
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> positionMatrix[0][4] = 99
>>> positionMatrix
([0, 0, 0, 0, 99, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

只要不要这样做:

>>> positionMatrix = [[0]*10]*3
>>> positionMatrix[0][4] = 99
>>> positionMatrix
[[0, 0, 0, 0, 99, 0, 0, 0, 0, 0], [0, 0, 0, 0, 99, 0, 0, 0, 0, 0], [0, 0, 0, 0, 99, 0, 0, 0, 0, 0]]
>>> 

这会指向内存中的同一个对象。

以防万一,你可以使用这个:

>>> positionMatrix = [[0]*10, [0]*10, [0]*10]
>>> positionMatrix
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
>>> positionMatrix[0][4] = 99
>>> positionMatrix
[[0, 0, 0, 0, 99, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

这样你就会创建三个不同的对象。

撰写回答