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

2018-04-26 17:09:48 +08:00
 U87

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

1063 次点击
所在节点    问与答
2 条回复
whoami9894
2018-04-26 17:17:56 +08:00
if 语句恒为 false
应该是
if word not in dict.keys()
U87
2018-04-26 17:29:21 +08:00
@whoami9894 谢谢我 sb 了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/450138

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX