![](/img/trans.png)
[英]Efficient creation of numpy arrays from list comprehension and in general
[英]creation of numpy array of arrays from list
我想從一個列表(下面的代碼中的nmax)創建一個數組數組。 我正在嘗試使用列表理解,但沒有得到預期的結果。 如果我手動分配行,它將按預期工作:
dummy[0] = np.linspace(1, nmax[0], len(nmax))
dummy[0]
array([ 1. , 1.00166722, 1.00333444, ..., 5.99666556,
5.99833278, 6. ])
dummy[2999] = np.linspace(1, nmax[2999], len(nmax))
dummy[2999]
array([ 1. , 1.01433811, 1.02867623, ..., 43.97132377,
43.98566189, 44. ])
但是通過列表理解,它給了我不同的結果:
dummy = [(np.linspace(1, nmax[i], len(nmax))) for i in nmax]
dummy[0]
array([ 1. , 1.00166722, 1.00333444, ..., 5.99666556,
5.99833278, 6. ])
dummy[2999]
array([ 1. , 1.00200067, 1.00400133, ..., 6.99599867,
6.99799933, 7. ])
從一個值到另一個值的變化是在索引2585上,我不知道為什么。
這是完整的代碼:
rho=7800
lamb = 500 * 10 **(-9)
#parameters
a = np.linspace(1e-9, 3000e-9, 3000)
x = a * 2*np.pi / lamb
nmax = [int(round(2+i+4*i**(1/3))) for i in x] # list
n = np.zeros((len(nmax), len(nmax)))
#dummy = [(np.linspace(1, nmax[i], len(nmax))) for i in nmax]
嘗試用dummy = [(np.linspace(1, i, len(nmax))) for i in nmax]
,您實際上正在做的是dummy[2999] = np.linspace(1, nmax[nmax[2999]], len(nmax))
而不是dummy[2999] = np.linspace(1, nmax[2999], len(nmax))
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.