我在 perl 中有這段代碼,它允許我創建一個 8 到 1 的串列并創建一個編號表。通過在“后綴”為 1 之前添加到串列資料(即 8 到 1)來填充陣列。即在陣列內部,我們將有 numrotation [1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1]。1 ..15然后用and15.1 15.2 15.3和的值填充陣列16..32
我想知道哪個功能可以代替推送功能。我將代碼放在 perl 中,而我在 python 中的測驗卻沒有: perl 中的代碼:
for ( reverse( 1 .. 8 ) ) { push @Numerotation, '1.' . $_ } push
@Numerotation, ( 1 .. 15, 15.1, 15.2, 15.3, 16 .. 31, 34 .. 45 );
python中的代碼(不起作用):
import numpy as np
lst = list(range(1,8 1))
lst.reverse()
print(lst)
numerotation= np.array()
for i in lst :
d=1. i
numerotation.append(d)
print(numerotation)
uj5u.com熱心網友回復:
由于您使用的是 numpy,因此您不能像使用常規 Python 串列那樣直接在陣列上進行追加。相反,您需要使用類函式append()。此外,由于np.array()需要輸入,您需要使用它np.empty(0)來創建一個空陣列。
import numpy as np
lst = list(range(1, 8 1))
lst.reverse()
print(lst)
numerotation = np.empty(0)
for i in lst :
d = "1." str(i)
numerotation = np.append(numerotation, d)
print(numerotation)
在您的 Perl 代碼中,您將浮點數創建為字串,因此在本示例中我將它們保留為這種方式。要使它們成為數字,您需要使用float(d).
這是另一種使用常規 Python 串列然后從中創建 numpy 陣列的方法。
import numpy as np
lst = list(range(1, 8 1))
lst.reverse()
print(lst)
numbers = ["1." str(i) for i in lst]
numerotation = np.array(numbers)
print(numerotation)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/485312.html
上一篇:檢查陣列和哈希是否為空
