list1 = [{'agent': 0, 'loc': (1, 2), 'timestep': 1}, {'agent': 1, 'loc': (1, 3), 'timestep': 2}]
我有這樣的字典串列,我想附加 10 個與原始串列的最后一個元素相同的專案,并將每個時間步的值增加一,以最終新附加的元素的時間步長按升序增加一. 我嘗試像下面那樣迭代,但它最終將所有時間戳值增加到了一個很大的數字。
for i in range(10):
list1.append(constraints[-1])
list1[-1]['timestep'] =1
任何幫助表示感謝謝謝
uj5u.com熱心網友回復:
嘗試添加.copy():
list1 = [
{"agent": 0, "loc": (1, 2), "timestep": 1},
{"agent": 1, "loc": (1, 3), "timestep": 2},
]
for i in range(10):
list1.append(list1[-1].copy())
list1[-1]["timestep"] = 1
print(list1)
印刷:
[
{"agent": 0, "loc": (1, 2), "timestep": 1},
{"agent": 1, "loc": (1, 3), "timestep": 2},
{"agent": 1, "loc": (1, 3), "timestep": 3},
{"agent": 1, "loc": (1, 3), "timestep": 4},
{"agent": 1, "loc": (1, 3), "timestep": 5},
{"agent": 1, "loc": (1, 3), "timestep": 6},
{"agent": 1, "loc": (1, 3), "timestep": 7},
{"agent": 1, "loc": (1, 3), "timestep": 8},
{"agent": 1, "loc": (1, 3), "timestep": 9},
{"agent": 1, "loc": (1, 3), "timestep": 10},
{"agent": 1, "loc": (1, 3), "timestep": 11},
{"agent": 1, "loc": (1, 3), "timestep": 12},
]
uj5u.com熱心網友回復:
您要附加的元素都指向記憶體中的同一位置(即淺拷貝,導致不良行為)。您可以通過使用串列推導來避免這種情況:
[{'agent': 0, 'loc': (1, 2), 'timestep': i} for i in range(1, 11)]
這輸出:
[
{'agent': 0, 'loc': (1, 2), 'timestep': 1},
{'agent': 0, 'loc': (1, 2), 'timestep': 2},
...
{'agent': 0, 'loc': (1, 2), 'timestep': 9},
{'agent': 0, 'loc': (1, 2), 'timestep': 10}
]
uj5u.com熱心網友回復:
您可以通過使用 .get() 資料結構并遍歷您的字典串列來增加時間步長。如果字典中的值為 none,.get() 還允許您命名默認值。
list1 = [{'agent': 0, 'loc': (1, 2), 'timestep': 1}, {'agent': 1, 'loc': (1, 3), 'timestep': 2}]
for dictionary in list1:
dictionary['timestep'] = dictionary.get('timestep') 1
print(list1)
.get() 的檔案可以在這里找到:https ://pythonexamples.org/python-dictionary-get/
我希望這有幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495557.html
下一篇:如何從txt檔案中讀取字典串列?
