我正在使用 Python 的集合庫來制作一個字典,其中鍵是整數,值是串列。我正在使用defaultdict(list)命令。我正在嘗試編輯這些串列中的元素,但沒有成功。
我認為串列理解應該適用于此,但我不斷收到語法錯誤。我附上我在下面嘗試過的內容:
import collections
test = collections.defaultdict(list)
test[4].append(1)
test[4].append(5)
test[4].append(6)
#This would yield {4: [1,5,6]}
run_lengths = [1,3,4,6] #dummy data
for i in run_lengths:
#I would like to add 3 to each element of these lists which are values.
test[i][j for j in test[i]] = i
uj5u.com熱心網友回復:
假設您想就地修改串列,您需要覆寫每個元素,因為整數是不可變的:
test[4][:] = [e 3 for e in test[4]]
輸出:
defaultdict(list, {4: [4, 8, 9]})
如果您不關心生成新物件(即您沒有將變數名鏈接到test[4]您可以使用:
test[4] = [e 3 for e in test[4]]
有什么區別?
第一種情況修改了串列。如果其他變數指向串列,則將反映更改:
x = test[4]
test[4][:] = [e 3 for e in test[4]]
print(x, test)
# [4, 8, 9] defaultdict(<class 'list'>, {4: [4, 8, 9]})
在另一種情況下,串列被替換為一個新的、獨立的、一個。所有潛在的系結都丟失了:
x = test[4]
test[4] = [e 3 for e in test[4]]
print(x, test)
# [1, 5, 6] defaultdict(<class 'list'>, {4: [4, 8, 9]})
在你的回圈中
假設run_lengths包含要更新的鍵串列:
for i in run_lengths:
test[i][:] = [e 3 for e in test[i]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410043.html
標籤:
上一篇:為字典值分配分數
下一篇:如何制作小塊python字典
