V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
U87
V2EX  ›  问与答

Python 字典来算一个字符在一个段落出现的次数,出现了报错。实在没找到原因 QAQ

  •  
  •   U87 · 2018-04-26 17:09:48 +08:00 · 1044 次点击
    这是一个创建于 2199 天前的主题,其中的信息可能已经有所发展或是发生改变。

    def calculate(s): list = s.split() dict = {} for word in list: if word not in list: dict[word] = 1 else: dict[word] += 1 return dict

    if name == 'main': words = "I Like python and you Like java too do you Like python or java" print calculate(words)

    报错:Traceback (most recent call last): File "D:/KDR/gg.py", line 15, in <module> print calculate(words) File "D:/KDR/gg.py", line 10, in calculate dict[word] += 1 KeyError: 'I'
    妈的居然报键值索引错误 2333

    2 条回复    2018-04-26 17:29:21 +08:00
    whoami9894
        1
    whoami9894  
       2018-04-26 17:17:56 +08:00 via Android
    if 语句恒为 false
    应该是
    if word not in dict.keys()
    U87
        2
    U87  
    OP
       2018-04-26 17:29:21 +08:00
    @whoami9894 谢谢我 sb 了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2178 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 11:09 · PVG 19:09 · LAX 04:09 · JFK 07:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.