我需要帮助创建一个名为strcount(S)
的函数,该函数返回一个以单词为键的字典,以及单词作为相应值出现的次数。输出应该如下所示:
strcount("a a a a b b")
{'a': 4, 'b': 2}
strcount("one")
{'one': 1}
sorted(strcount("this one and that one for one time").items())
[('and', 1), ('for', 1), ('one', 3), ('that', 1), ('this', 1), ('time', 1)]
最典型的解决方案是使用
collections.Counter
:如果您想编写自己的解决方案,我会尝试如下方法:
.split()
进行此操作。在0
。在1
添加到your_dict[word]
。在@Blender使用^{} 的回答很好,但它适用于Python 2.7及更高版本。在
下面是一个适用于较低版本Python的替代解决方案:
这将为您提供:
^{pr2}$或者,您可以不使用Counter来实现自己的算法。
如果使用的是Python 3.x,请替换以下行:
^{pr2}$有:
输出:
相关问题 更多 >
编程相关推荐