如何更新字典计数器?

时间:2018-11-08 08:57:06

标签: python-3.x dictionary counter

让我们说您有一个这样的字典计数器:

themes_and_likes = {“幻想”:0,“恐怖”:0}

如何更新它,以便每当源文件中出现各个单词时,它就会增加?

我的回答是:

for i in usa_video_comments:

    if themes_and_likes["fantasy"]:
        themes_and_likes["fantasy"] += 1
    else:
        themes_and_likes["horror"] = 1
print(themes_and_likes)

其中usa_video_comments是来源,我收到的答案是

{'fantasy':0,'horror':1}

这是错误的,因为计数器没有连续更新

1 个答案:

答案 0 :(得分:0)

您的if语句始终求值为False,因为, if themes_and_likes["fantasy"]:即将成为if 0:,并且您在else语句中除了分配1值之外,也没有做其他事情。在不知道文件结构的情况下,很难准确回答。但是假设您知道自己在做什么,下面的代码片段可能会对您有所帮助。

themes_and_likes = {"fantasy":0, "horror":0}

for i in usa_video_comments: # assuming i is single line comment

    if 'fantasy' in i:
        themes_and_likes["fantasy"] += 1
    elif 'horror' in i:
        themes_and_likes["horror"] += 1

print(themes_and_likes)
相关问题