Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

搜索未果,希望能够得到帮助:

现在有一个字典

dict = {'A1':12 24 42} 

现在我需要得到这个字典中同一个 key 的值,即返回 12+24+42的结果,要如何合并呢?(value 有多个,不一定为 3 个)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
405 views
Welcome To Ask or Share your Answers For Others

1 Answer

Python中一个字典的一个键是不能有多个值的
上面的写法不正确
如果要一个键多个值的话,就要使用列表存值

dic = {'A1':[12,24,42]}

这样求和也很方便了,只要

for key in dic:
    dic[key] = sum(dic[key])
print(dic) # {'A1': 78}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...