简体   繁体   English

如何更优雅地构造2的幂的numpy数组?

[英]How to construct a numpy array of numbers of powers of 2 more elegantly?

I would like to figure out how i can create this array without putting every single value in per hand. 我想弄清楚如何可以创建此数组而不必每手放每个值。

Is there a way how i can use the information that every value is the doubled value of its predecessor, except for the first? 有没有一种方法可以使用除第一个值以外的每个值都是其前身值的两倍的信息?

My Code is as follows: 我的代码如下:


import numpy as np

Matrix = np.array([1,2,4,8,16,32,64,128,256]).reshape (3,3)

print(Matrix)

You can use np.arange , and take advantage of the fact that they are powers of 2 : 您可以使用np.arange ,并利用它们是2幂的事实:

2**np.arange(9).reshape(-1, 3)

array([[  1,   2,   4],
       [  8,  16,  32],
       [ 64, 128, 256]], dtype=int32)

You could also do something like this: 您还可以执行以下操作:

var myRandomArray = [1];
var i = 1;
var num = 1;
while (i < 9) {
  myRandomArray.push(num = num * 2);
  i = i + 1;
}

This is written in JavaScript. 这是用JavaScript编写的。 For Python, just switch what you need around, the main idea is still there. 对于Python,只需切换所需的内容,主要思想仍然存在。 I believe in Python, it is append instead of push. 我相信Python,它是添加而不是推送。

You could use np.vander : 您可以使用np.vander

np.vander([2], 9, True).reshape(3, 3)
# array([[  1,   2,   4],
#        [  8,  16,  32],
#        [ 64, 128, 256]])

Here's a jury-rigged solution: 这是陪审团操纵的解决方案:

In [10]: total_num = 9 

In [11]: np.array([2**n for n in range(0, total_num)]).reshape(3, -1) 
Out[11]: 
array([[  1,   2,   4],
       [  8,  16,  32],
       [ 64, 128, 256]])

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

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