将for循环结果转换为numpy数组

时间:2019-09-18 03:42:34

标签: python python-3.x numpy

我想创建一个由17个元素组成的数组,这些元素以1开头,其他数字分别是紧接其前的值的两倍。

我到目前为止所拥有的是:

import numpy as np


array = np.zeros(shape=17)

array[0]=1

x = 1

for i in array:
    print(x)
    x *= 2

print(array)

我得到的是:

1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

我想要的是:

[1.2.4.8.16.32.64.128.256.512.1024.2048.4096.8192.16384.32768.65536]

3 个答案:

答案 0 :(得分:1)

有一个功能

np.logspace(0,16,17,base=2,dtype=int)
# array([    1,     2,     4,     8,    16,    32,    64,   128,   256,
#          512,  1024,  2048,  4096,  8192, 16384, 32768, 65536])

替代品:

1<<np.arange(17)
2**np.arange(17)
np.left_shift.accumulate(np.ones(17,int))
np.repeat((1,2),(1,16)).cumprod()
np.vander([2],17,True)[0]
np.ldexp(1,np.arange(17),dtype=float)

愚蠢的选择:

from scipy.sparse import linalg,diags
linalg.spsolve(diags([(1,),(-2,)],(0,-1),(17,17)),np.r_[:17]==0    
np.packbits(np.identity(32,'?')[:17],1,'little').view('<i4').T[0] 
np.ravel_multi_index(np.identity(17,int)[::-1],np.full(17,2))
np.where(np.sum(np.ix_(*17*((0,1),))).reshape(-1)==1)[0]

答案 1 :(得分:0)

您需要将值分配回

import numpy as np


array = np.zeros(shape=17, dtype="int")

x = 1

for i in range(len(array)):
    array[i] = x
    print(x)
    x *= 2

>>> print(array)
[    1     2     4     8    16    32    64   128   256   512  1024  2048
  4096  8192 16384 32768 65536]

答案 2 :(得分:0)

使用numpy矢量化将更加有效,如下所示。

import numpy as np
n=17
triangle = (np.tri(n,n,-1, dtype=np.int64)+1)
triangle.cumprod(axis=1)[:,-1]

说明

np.tri(n,n, dtype=np.int64)将创建三角形矩阵,其对角线及对角线以下为1,其他值为0,其中

np.tri(n,n, -1, dtype=np.int64)将三角形矩阵移动一行,以使第一行全为零

np.tri(n,n, -1, dtype=np.int64)+1会将0s更改为1s,将1s更改为2s

在最后一步使用cumprod并接受最后一列,这是我们的答案,因为它将是0,1,2 ... n 2的乘积,其余1s