這個問題在這里已經有了答案: 串列更改意外地反映在子串列中的串列 (17個答案) 昨天關門。
語境:
- 蟒蛇 3.9
- 我有一個
thetas包含 2 個值的串列。我用一些初始值啟動這個串列。我打算在每次迭代時就地更新這個串列。 - 我有另一個串列
theta_history,我打算使用函式存盤thetas每次迭代的值。update_thetas
問題:
theta_history最終成為長度 = 的串列iterations,但只有thetas重復的最終值,而不是每次迭代的值。
方法(我正在使用.append(),但也嘗試使用.insert(ind, val)- 結果相同)
def update_thetas(thetas):
for i in range(len(thetas)):
thetas[i] = thetas[i] 1
print(f"thetas: {thetas}")
return thetas
thetas = [0] * 2
thetas[0] = 10
thetas[1] = 5
theta_history = []
iterations = 3
for i in range(iterations):
theta_history.append(thetas)
thetas = update_thetas(thetas)
print(f"theta_history: {theta_history}")
這會產生:
thetas: [11, 6]
thetas: [12, 7]
thetas: [13, 8]
theta_history: [[13, 8], [13, 8], [13, 8]]
我想要的是:
theta_history: [[11, 6], [12, 7], [13, 8]]
謝謝!
uj5u.com熱心網友回復:
您只是將參考存盤在 中theta_history,因此每次都需要制作串列的副本。
您可以使用展開運算子 ( *) 進行簡單復制。如果你正在做一些更復雜的內臟,你需要做一個深拷貝(你可以在網上搜索)。
for i in range(iterations):
theta_history.append([*thetas])
thetas = update_thetas(thetas)
print(f"theta_history: {theta_history}")
輸出:
thetas: [11, 6]
thetas: [12, 7]
thetas: [13, 8]
theta_history: [[10, 5], [11, 6], [12, 7]]
uj5u.com熱心網友回復:
您可以復制thetasusinglist或tuplefunction 的值,而不是附加對 的參考thetas。
theta_history.append(tuple(thetas))
foo = ["a", "b", "c"] # original list
bar = foo # a reference to foo
baz = list(foo) # copy value of foo into baz
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/493746.html
標籤:Python python-3.x 列表
