gpt4 book ai didi

python - 如何在列表中搜索字典键

转载 作者:太空宇宙 更新时间:2023-11-03 17:13:54 24 4
gpt4 key购买 nike

假设我有一本字典:

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5, 'elections': 5}

我有一个列表:

mylist = [['a new', 'party'], ['to', 'lol'], ['compete'], ['in', 'adore', 'the 2013'], ['federal', 'elections'], ['The Free', 'Voters'], ['leadership', 'declined to'], ['join forces', 'according to', 'a leaked'], ['email from', 'Bernd Lucke'], ['Advocating', 'adore'] ]

我希望能够在列表中搜索字典中的键。如果列表中的单词是键,则获取该键的值并将其添加到计数器中。最后,得到所有值的总和。

有办法做到这一点吗?

最佳答案

像这样吗?

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5, 'elections': 5}
mylist = [['a new', 'party'], ['to', 'lol'], ['compete'], ['in', 'adore', 'the 2013'], ['federal', 'elections'], ['The Free', 'Voters'], ['leadership', 'declined to'], ['join forces', 'according to', 'a leaked'], ['email from', 'Bernd Lucke'], ['Advocating', 'adore']]

print([lst.get(i) for j in mylist for i in j if lst.get(i) != None])
print(sum([lst.get(i) for j in mylist for i in j if lst.get(i) != None]))

输出:

[10, 5, 10]
25
<小时/>

如果您不喜欢它们一行:

total = []

for i in mylist:
for j in i:
if lst.get(i) != None:
total.append(lst.get(i))

print(sum(total))

关于python - 如何在列表中搜索字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826229/

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