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

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

我想弄清楚如何在不将每个值都放在每只手上的情况下创建这个数组。

有什么方法可以让我知道除了第一个值之外,每个值都是其前身值的两倍?

我的代码如下:


import numpy as np

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

print(Matrix)

您可以使用 np.arange,并利用它们是 2 的幂这一事实:

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

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

你也可以这样做:

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

这是在JavaScript中写的。对于Python,随便切换你需要的东西,主要思想还在。我相信Python,它是append而不是push。

这是一个 jury-rigged 解决方案:

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]])

你可以使用 np.vander:

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