我有一本字典,如:d = {c1: l1, c2: l2, c3: l3, ......., cn: ln}其中 c1, c2,.... cn 是字符串,l1, l2,... l3 是列表?,F在,我有一個需要更新列表的函數,對于一對變量 c、x:1. 如果 c 在 d 中:找到c的(key, value),用x更新對應的l2. 如果 c 不在 d 中:在 d 中創建一個 cm: lm 對到目前為止,我嘗試過的是:if c in d: d.update({cn:ln.append(x)})else: d.update({cm:lm.insert(x)})但是代碼沒有按預期工作。任何有關為什么代碼不起作用的指針都會有所幫助,并且歡迎對可以使其工作的代碼提出任何建議。PS: c 和 x 值作為參數傳遞給一個函數,所有更新都在這里發生。為了澄清起見,我在 Windows 10 上的 PyCharm 上運行 Python 2.7。編輯:
2 回答

小唯快跑啊
TA貢獻1863條經驗 獲得超2個贊
if c in d:
# d[c] corresponds to the list you want to update
d[c].append(x)
# the append function directly modifies the list at d[c],
# so we don't have to do any re-assignment
else:
# d[c] does not exist, so we create a new list with your item
d[c] = [x]

一只名叫tom的貓
TA貢獻1906條經驗 獲得超3個贊
請參閱https://repl.it/repls/ExternalCornyOpendoc 示例代碼如下:
d = {
"Key1":[1,2,3],
"Key2":[11,12,13]
}
def test(c, x):
if c in d:
d[c].append(x);
else:
d[c] = [x];
print(d)
test("Key1", 12)
test("Key3", 122)
添加回答
舉報
0/150
提交
取消