Python 如何生成二维 numpy 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28628773/
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-19 03:32:10  来源:igfitidea点击:

How to generate 2d numpy array?

pythonnumpygenerator

提问by Taygrim

I'm trying to generate a 2d numpy array with the help of generators:

我试图在生成器的帮助下生成一个 2d numpy 数组:

x = [[f(a) for a in g(b)] for b in c]

And if I try to do something like this:

如果我尝试做这样的事情:

x = np.array([np.array([f(a) for a in g(b)]) for b in c])

I, as expected, get a np.array of np.array. But I want not this, but ndarray, so I can get, for example, column in a way like this:

正如预期的那样,我得到了一个 np.array 的 np.array。但我想要的不是这个,而是 ndarray,所以我可以像这样获得列:

y = x[:, 1]

So, I'm curious whether there is a way to generate it in such a way.

所以,我很好奇是否有办法以这种方式生成它。

Of course it is possible with creating npdarray of required size and filling it with required values, but I want a way to do so in a line of code.

当然,可以创建所需大小的 npdarray 并用所需的值填充它,但我想要一种在一行代码中这样做的方法。

采纳答案by Marijn van Vliet

This works:

这有效:

a = [[1, 2, 3], [4, 5, 6]]
nd_a = np.array(a)

So this should work too:

所以这也应该有效:

nd_a = np.array([[x for x in y] for y in a])