简体   繁体   English

如何创建一个列表长度为零的numpy数组?

[英]How to create a numpy array of zeros of a list's length?

I have a list, say 我有一个清单,说

a = [3, 4, 5, 6, 7]

And i want to create a numpy array of zeros of that list's length. 我想创建该列表长度为零的numpy数组。

If I do 如果我做

b = np.zeros((len(a), 1))

I get 我懂了

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

instead of 代替

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

What is the best way to get the latter option? 获得后一种选择的最佳方法是什么?

If you don't want to have to care about shapes, use np.zeros_like : 如果您不想关心形状,请使用np.zeros_like

np.zeros_like(a)
# array([0, 0, 0, 0, 0])

There's also the option of querying np.shape : 还有查询np.shape的选项:

np.zeros(np.shape(a))
# array([0., 0., 0., 0., 0.])

Both options should work for ND lists as well. 这两个选项也应适用于ND列表。

You passed two-element tuple to zeros , so it produced 2D array, you can simply pass integer to zeros 您将两个元素的tuple传递给zeros ,这样就产生了2D数组,您可以简单地将整数传递给zeros

a = [3, 4, 5, 6, 7]
b = np.zeros(len(a))
print(b) #prints [ 0.  0.  0.  0.  0.]

You can try this 你可以试试这个

np.zeros(len(a), dtype=np.int)

It will return 它将返回

array([0, 0, 0, 0, 0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM