st="New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3"
list1=list(st.split(" "))
print(list1)
dict1=dict()
for i in list1:
if i in dict1:
dict1[i]=1
else:
dict1[i]+=1
print(sorted(dict1))
老是会报错keyerror,不知道为什么?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
菜猫小六 2021-12-07 10:38关注盲猜一下,这是要统计单词出现的频率嘛。
如果这个词不在最后的字典中,那么把这个词添加进去,并且这个词的次数置1,如果在,那么这个词出现的次数+1。
题主把判断的条件搞反了。(如有异议,我是垃圾)st = "New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3" list1 = list(st.split(" ")) print(list1) dict1 = dict() for i in list1: if i in dict1: dict1[i] += 1 else: dict1[i] = 1 print dict1本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报