假設我們有 list a = [3,4,2,1],a我們想從中獲得以下陣列:b = [0,0,0,1,1,1,1,2,2,3]。
我設法做到了這樣:
import numpy as np
a = [3,4,2,1]
b = np.concatenate([[i] * n for i, n in enumerate(a])
print(b)
輸出:
array([0, 0, 0, 1, 1, 1, 1, 2, 2, 3])
哪個作業正常,但我不禁想知道是否有更好的方法?
編輯
@mathfux 的解決方案比我的解決方案更優雅,只需使用np.repeat. 我使用 對兩者進行perfplot了基準測驗,結果如下:
基準代碼:
import numpy as np
import perfplot
out = perfplot.bench(
setup=lambda n: np.arange(n),
kernels=[
lambda x: np.concatenate([[i] * n for i, n in enumerate(x)]),
lambda x: np.repeat(range(len(x)), x)
],
n_range=np.arange(128, 128 * 16, 128),
labels=[
"concat",
"repeat"
],
xlabel='np.arange(x)'
)
out.show()
uj5u.com熱心網友回復:
嘗試np.repeat:np.repeat([0,1,2,3], [3,4,2,1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424150.html
上一篇:將日期范圍轉換為整數序列
