這看起來應該很簡單,但我很難過(對 numpy 來說也很新。)
我有一個一維整數陣列a。
我想生成一個新的一維陣列b使得:
- 在元件的數量b等于在元素的和一
- 中的值b等于由相應的元件以分開的一些任意常數一個。
這是一口,所以這里有一個我想讓它更具體的例子:
a = array([2,3,3,4])
CONSTANT = 120
.
.
.
b = array([60,60,
40,40,40,
40,40,40,
30,30,30,30])
任何幫助表示贊賞!
uj5u.com熱心網友回復:
我認為一個非常明確的方法是
import numpy as np
a = np.array([2,3,3,4])
constant = 120
#numpy.repeat(x,t) repeats the val x t times you can use x and t as vectors of same len
b = np.repeat(constant/a , a)
uj5u.com熱心網友回復:
你可以用np.concatenate老式的來做到這一點zip:
>>> elements = CONSTANT / a
>>> np.concatenate([np.array([e]*n) for e, n in zip(elements, a)])
array([60., 60., 40., 40., 40., 40., 40., 40., 30., 30., 30., 30.])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/339471.html
