3 回答

TA貢獻1824條經驗 獲得超5個贊
您重復分配給 new_data,覆蓋以前的更改。
IE:
new_data[j] = data[j]*2 # won't work data[j] = data[j]*2 # will work.

TA貢獻1775條經驗 獲得超8個贊
初始化new_data并data刪除else.
編輯: 這應該回答你,它更有效,因為你在整個數組中迭代你擁有的間隔數,這對于大輸入來說會很慢,但在這里你將遍歷數組一次。如果你想將其他元素增加三倍,一個天真的解決方案是在循環new_data之前乘以 3 ,所以把.fornew_data = np.copy(data)*3
import numpy as np
data = np.array([0,1,2,8,4,5,6,5,4,5,6,7,8])
start = np.array([0,5,7])
end = np.array([3,6,9])
new_data = np.copy(data) # change to new_data = np.copy(data)*3 to triple other elements.
for i in range(len(start)):
for j in range(start[i], end[i]+1):
new_data[j] = data[j]*2
您的代碼中的另一個注意事項是(j >= start[i]) & (j <= end[i]),這可以簡化為start[i] <= j <= end[i],可能更快。

TA貢獻1806條經驗 獲得超8個贊
我建議使用 python 的zip命令來同時解壓縮多個列表。
代碼說明:由于不屬于任何子列表的數據點保持不變,我使用 numpy 的copy方法來創建原始數據的新副本。然后我將您想要的子列表乘以兩個。
import numpy as np
data = np.array([0, 1, 2, 8, 4, 5, 6, 5, 4, 5, 6, 7, 8])
start = np.array([0, 5, 7])
end = np.array([3, 6, 9])
new_data = data.copy() #Not to mess up our original dataset.
for s, e in zip(start, end):
new_data[s:e+1] *= 2 #Because it's an inclusive set.
添加回答
舉報