我正在嘗試在 python 中運行一個看起來像這樣的 for 回圈:
data = np.linspace(0.5, 50, 10)
output = []
for i in data:
x = data[i] - data[i 1]
output.append(data)
但我不斷收到錯誤:
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
作為參考,我希望代碼執行以下操作:
x1 = x = 資料[0] - 資料[1]
x2 = x = 資料[1] - 資料[2] ...
并將其輸出到串列中。
任何幫助將非常感激
uj5u.com熱心網友回復:
這里有幾件事:
- 您正在迭代實際元素,而不是它們的索引。要迭代索引,您可以執行以下操作
for index in range(len(data) - 1))。 - 如上所示,
len(data) - 1為了避免越界,您想要迭代直到。 - 看來您正在計算
x,但最終還是追加data了。 - 為了獲得可讀的代碼,重要的是給變數賦予有意義的名稱(
i并且x沒有意義)。
data = np.linspace(0.5, 50, 10)
output = []
for index in range(len(data) - 1):
result = data[index] - data[index 1]
output.append(result)
uj5u.com熱心網友回復:
for i in data:直接回圈data,因此i將是 中的每個元素data,而不是它的索引。如果您需要索引,請使用enumerate():
output = []
for i, elem in enumerate(data):
x = data[i] - data[i 1]
output.append(data)
但是,這行不通,因為最后會發生越界錯誤。相反,您可以使用內置的 numpy 功能:
output = data[:-1] - data[1:]
print(output)
輸出:
array([-5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5])
或可能的解決方案:
np.full(9, -5.5)
np.ones(9) * -5.5
uj5u.com熱心網友回復:
IIUC,你想計算連續的差異,但反過來。您可以使用numpy.diff
np.diff(data[::-1])[::-1]
其他選項,通過取除最后一個/第一個元素之外的所有元素并減去:
data[:-1] - data[1:]
輸出:array([-5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5, -5.5])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/441548.html
標籤:Python python-3.x 麻木的 循环 for循环
上一篇:由于“找不到最佳引數”錯誤[python],無法使用來自scipy的curve_fit()將曲線擬合到資料點
下一篇:多個檔案作為函式輸入
