保持if语句中的值

时间:2013-08-17 22:14:15

标签: 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

我的例子会给我:

[10]
[5]

虽然我想要15,最好在循环之外,就像现实生活中的代码一样,单词不是单个字符串,而是许多正在循环的字符串。 任何人都可以帮我这个吗?

3 个答案:

答案 0 :(得分:5)

这是一个非常简单的例子,它打印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())

答案 1 :(得分:1)

你应该在循环之外声明计数器。您在代码中执行的所有其他操作都是正确的。 正确的代码:

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

print counter

答案 2 :(得分:1)

我不确定你在使用该代码做什么,因为我没有看到任何循环。但是,做你想做的事情的方法如下:

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