gpt4 book ai didi

python - 保留 if 语句中的值

转载 作者:行者123 更新时间:2023-11-28 20:47:41 28 4
gpt4 key购买 nike

我正在编写一个代码,它将遍历单词中的每个单词,在字典中查找它们,然后将字典值附加到计数器。但是,如果我打印计数器,我只会从我的 if 语句中获取最后一个数字(如果有的话)。如果我将 print counter 放在循环内,那么我会得到每个单词的所有数字,但没有总值。我的代码如下:

dictionary = {word:2, other:5, string:10}
words = "this is a string of words you see and other things"
if word in dictionary.keys():
number = dictionary[word]
counter += number
print counter

我的例子会给我:

[10]
[5]

虽然我想要 15,但最好在循环之外,因为在现实生活中的代码中,words 不是单个字符串,而是正在循环的许多字符串。谁能帮我解决这个问题?

最佳答案

这是一个非常简单的示例,打印 15:

dictionary = {'word': 2, 'other': 5, 'string': 10}
words = "this is a string of words you see and other things"

counter = 0
for word in words.split():
if word in dictionary:
counter += dictionary[word]
print counter

请注意,您应该在循环之前声明 counter=0 并使用 word in dictionary 而不是 word in dictionary.keys()

你也可以使用 sum() 在一行中写同样的东西:

print sum(dictionary[word] for word in words.split() if word in dictionary)

或:

print sum(dictionary.get(word, 0) for word in words.split())

关于python - 保留 if 语句中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18293774/

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