Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 保留if语句中的值_Python_If Statement - Fatal编程技术网

Python 保留if语句中的值

Python 保留if语句中的值,python,if-statement,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 dictiona

我正在编写一个代码,它将遍历单词中的每个单词,在字典中查找它们,然后将字典值附加到计数器。然而,如果我打印计数器,我只能从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
sum(dictionary[word] for word in words.split() if word in dictionary)
我的例子将告诉我:

[10]
[5]
虽然我想要
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
请注意,您应该在循环之前声明
counter=0
,并使用字典中的
word
而不是dictionary.keys()中的
word

您也可以使用
sum()
在一行中写入相同的内容:

或:


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

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

我不确定你在用这些代码做什么,因为我没有看到任何循环。但是,可以通过以下方式实现您的愿望:

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
sum(dictionary[word] for word in words.split() if word in dictionary)

如果字典中的单词:
就足够了,而且速度更快
dictionary.keys()
首先必须创建一个列表对象,然后中的
操作员必须扫描该列表
word in dictionary
只需计算哈希值即可查看键是否存在,这是一个O(1)常量时间操作。我的示例将给出否,它不会
code+=number
将给您一个
NameError
UnboundLocalError
,因为
计数器在别处没有定义。它也不会打印
[…]
,因为这意味着您要打印一个元素列表。