gpt4 book ai didi

python - 将字典中的键与字符串列表进行比较并对值求和

转载 作者:行者123 更新时间:2023-11-30 23:04:33 25 4
gpt4 key购买 nike

所以我制作了一本字典,键是单词,值是与每个单词相关的数值。我还有一个单词列表。我想取出列表中的单词,看看它们是否在字典中。如果列表中的单词在字典中,我需要能够将与每个单词关联的值相加。

dictionary = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
list = ["I", "am", "so", "happy", "this", "is", "the", "greatest", "day", "ever", "I", "am", "so", "excited", "!"]

最佳答案

使用列表理解:

dictionary = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
lst = ["I", "am", "so", "happy", "this", "is", "the", "greatest", "day", "ever", "I", "am", "so", "excited", "!"]

print sum([dictionary[i] for i in lst if i in dictionary])

关于python - 将字典中的键与字符串列表进行比较并对值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33659192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com