创建多维零 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15393216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:01:09  来源:igfitidea点击:

Create Multidimensional Zeros Python

pythonarraysmultidimensional-arraynumpy

提问by Sameer Patel

I need to make a multidimensional array of zeros.

我需要制作一个多维零数组。

For two (D=2) or three (D=3) dimensions, this is easy and I'd use:

对于两个 (D=2) 或三个 (D=3) 维度,这很容易,我会使用:

a = numpy.zeros(shape=(n,n)) 

or

或者

a = numpy.zeros(shape=(n,n,n))

How for I for higher D, make the array of length n?

对于更高的 D,我如何制作长度为 n 的数组?

采纳答案by mgilson

You can multiply a tuple (n,)by the number of dimensions you want. e.g.:

您可以将元组乘以(n,)所需的维数。例如:

>>> import numpy as np
>>> N=2
>>> np.zeros((N,)*1)
array([ 0.,  0.])
>>> np.zeros((N,)*2)
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> np.zeros((N,)*3)
array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.]]])

回答by ev-br

>>> sh = (10, 10, 10, 10)
>>> z1 = zeros(10000).reshape(*sh)
>>> z1.shape
(10, 10, 10, 10)

EDIT: while above is not wrong, it's just excessive. @mgilson's answer is better.

编辑:虽然上面没有错,但它只是过分了。@mgilson 的回答更好。

回答by NPE

In [4]: import numpy

In [5]: n = 2

In [6]: d = 4

In [7]: a = numpy.zeros(shape=[n]*d)

In [8]: a
Out[8]: 
array([[[[ 0.,  0.],
         [ 0.,  0.]],

        [[ 0.,  0.],
         [ 0.,  0.]]],


       [[[ 0.,  0.],
         [ 0.,  0.]],

        [[ 0.,  0.],
         [ 0.,  0.]]]])

回答by Marko

you can make multidimensional array of zeros by using square brackets

您可以使用方括号制作多维零数组

array_4D = np.zeros([3,3,3,3])