【问题标题】:How to update a dictionary counter?如何更新字典计数器?
【发布时间】:2018-11-08 08:57:06
【问题描述】:

假设您有一个这样的字典计数器:

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_cmets 是来源,我收到的答案是

{'幻想':0,'恐怖':1}

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

【问题讨论】:

  • 你能展示一下文件的样子吗
  • 文件很大,但这里是其中的一部分:[ [ #Row 0 'XpVt6Z1Gjjo', #Video Id - Index 0 "我从一开始就关注你您的 vine 频道的所有 365 个视频博客",#Comment Text - Index 1 '3',#Likes - Index 2 '0'],#Replies - Index 3 [#Row 1 'XpVt6Z1Gjjo',#Video Id - Index 0 '向 Kong 打个招呼,为我特立独行',#Comment Text - Index 1 '3',#Likes - Index 2 '0'#Replies - Index 3 ] ]
  • 请将其添加到问题中并正确格式化

标签: python-3.x dictionary counter


【解决方案1】:

您的 if 语句始终计算为 False,因为, if themes_and_likes["fantasy"]: 正在变成 if 0: 并且您在 else 语句中没有做太多事情,除了为其分配值 1。在不知道文件结构的情况下,很难准确回答。但是,假设您知道自己在做什么,那么 sn-p 可能会对您有所帮助。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2023-04-11
    • 2022-11-08
    • 2020-09-05
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多