Shi*_*ifu 2 python if-statement
我正在编写一个代码,用于翻译单词中的每个单词,在字典中查找它们,然后将字典值附加到计数器中.但是,如果我打印计数器,我只从if语句中获取最后一个数字,如果有的话.如果我将打印计数器放在循环中,那么我会得到每个单词的所有数字,但没有总值.我的代码如下:
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
Run Code Online (Sandbox Code Playgroud)
我的例子会给我:
[10]
[5]
Run Code Online (Sandbox Code Playgroud)
虽然我想要15,最好在循环之外,就像现实生活中的代码一样,单词不是单个字符串,而是许多正在循环的字符串.谁能帮我这个?
这是一个非常简单的例子,它打印出来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
Run Code Online (Sandbox Code Playgroud)
请注意,您应该counter=0在循环之前声明并使用word in dictionary而不是word in dictionary.keys().
您也可以使用sum()以下方法在一行中编写相同的内容:
print sum(dictionary[word] for word in words.split() if word in dictionary)
Run Code Online (Sandbox Code Playgroud)
要么:
print sum(dictionary.get(word, 0) for word in words.split())
Run Code Online (Sandbox Code Playgroud)