簡體   English   中英

在Python中優雅地初始化n維矩陣

[英]Initializing an n-dimensional matrix elegantly in Python

關於SO如何初始化二維矩陣有幾個問題,答案是這樣的:

matrix = [[0 for x in range(10)] for x in range(10)]

有什么方法可以將其推廣到n維,而無需使用塊或寫出很長的嵌套列表推導?

由於整數是不可變的,因此您可以將代碼簡化為:

matrix = [[0] * 10 for x in range(10)]

正如@iCodez在評論中提到的,如果可以選擇NumPy,則可以簡單地執行以下操作:

import numpy as np                                              
matrix = np.zeros((10, 10)) 

如果您真的想要一個矩陣, np.zerosnp.ones可以快速創建一個二維數組來實例化矩陣:

import numpy as np
my_matrix = np.matrix(np.zeros((10,10)))

要歸納為n個維度,您不能使用根據定義為2維的矩陣:

n_dimensions = 3
width = 10

n_dimensional_array = np.ones((width,) * n_dimensions)

我同意,如果可以選擇numpy,則它是處理矩陣的一種簡單得多的方法。 我強烈推薦它。

就是說,此遞歸函數是將代碼泛化為n維的一種合理方法。 第一個參數是一個列表或元組,用於指定每個尺寸應多大(以及間接地多少個維)。 第二個參數是用於填充矩陣的常量值(在您的示例中為0 ):

def init(sizes, value=0):
    if (len(sizes) == 1):
        return [value] * sizes[0]
    else:

        # old code - fixed per comment. This method does not create
        # sizes[0] *new* lists, it just repeats the same list
        # sizes[0] times. This causes unexpected behavior when you
        # try to set an item in a list and all of its siblings get
        # the same change
        # return [init(sizes[1:], value)] * sizes[0]

        # this method works better; it creates a new list each time through
        return [init(sizes[1:], value) for i in xrange(sizes[0])]

matrix = init((2,3,4), 5)
matrix[0][0][0] = 100 # setting value per request in comment
print matrix
>>> [[[100, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]], [[5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]]]

N維數組很難在2D屏幕上打印,但是您可以在我手動縮進的代碼段中更輕松地看到matrix的結構。 它是一個長度為2的數組,包含長度為3的數組,包含長度為4的數組,其中每個值都設置為5:

[
    [
        [100, 5, 5, 5],
        [5, 5, 5, 5],
        [5, 5, 5, 5]
    ],
    [
        [5, 5, 5, 5],
        [5, 5, 5, 5],
        [5, 5, 5, 5]
    ]
]

@ brian-putman更快,更好...無論如何,這是我的解決方案:

init = lambda x, y: [init(x, y-1) if y>1 else 0 for _ in xrange(x)]

僅生成大小為x的正方形矩陣,並在y維度中填充零。 這樣叫

init(5, 3)

[[[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],
  [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],
  [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],
  [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],
  [0, 0, 0, 0, 0]]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM