【发布时间】:2013-12-05 18:25:09
【问题描述】:
所以基本上我需要程序来计算每个字母在一个句子中使用了多少次。 我唯一发现的就是这个,而且很丑:
from collections import Counter
str = "Mary had a little lamb"
counter = Counter(str)
print counter['a']
print counter['b']
print counter['c']
print counter['d']
print counter['e']
print counter['f']
#etc to z
有更简单的方法吗????
【问题讨论】:
-
您提到的代码实际上比您在大多数其他语言中获得的代码更简单(感谢有用的
collections模块)。除非您想知道如何编写for循环...是这样吗? -
看看this answer。您需要自己编写计数代码,但这可以帮助您入门。
-
不确定你认为哪个方面丑。计数操作只有两行(导入 Counter 类,然后创建 Creater 实例)。是你觉得丑陋的
print语句的继承吗?当然,一旦获得信息,就有一百万种不同的方式来使用/呈现信息。
标签: python python-2.7