Python 将for循环结果转换为numpy数组
我想创建一个包含17个元素的数组,这些元素以1开头,其他数字都是其前面值的两倍 到目前为止,我得到的是:Python 将for循环结果转换为numpy数组,python,python-3.x,numpy,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
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]
您需要重新分配该值
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]
使用如下所示的numpy矢量化将更有效 将numpy作为np导入 n=17 三角形=np.trin,n,-1,dtype=np.int64+1 三角形.cumprodaxis=1[:,-1] 解释 np.trin,n,dtype=np.int64将创建一个三角形矩阵,其值在对角线处和下方为1,在其他位置为0 np.trin,n,-1,dtype=np.int64将三角形矩阵移动一行,使第一行全部为零 np.trin,n,-1,dtype=np.int64+1将0更改为1s,1s更改为2s
在最后一步,使用cumprod并取最后一列,这是我们的答案,因为它将是0,1,2。。。n 2与剩余的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<<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]