Python 保留if语句中的值
我正在编写一个代码,它将遍历单词中的每个单词,在字典中查找它们,然后将字典值附加到计数器。然而,如果我打印计数器,我只能从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
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
,因为计数器在别处没有定义。它也不会打印[…]
,因为这意味着您要打印一个元素列表。