我有一本字典,如:d = {c1: l1, c2: l2, c3: l3, ......., cn: ln}其中 c1, c2,.... cn 是字符串,l1, l2,... l3 是列表。现在,我有一个需要更新列表的函数,对于一对变量 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
提交
取消