在Python中计算字符串中的字母数量
我需要写一个函数,countLetters(word)
,这个函数接收一个单词作为参数,然后返回一个列表,里面统计每个字母出现的次数。字母需要按照字母表的顺序排列。
这是我尝试的代码:
def countLetters(word):
x = 0
y = []
for i in word:
for j in range(len(y)):
if i not in y[j]:
x = (i, word.count(i))
y.append(x)
return y
我一开始试着写的时候没有用 if i not in y[j]
。
countLetters("google")
结果是
[('g', 2), ('o', 2), ('o', 2), ('g', 2), ('l', 1), ('e', 1)]
而我想要的是
[('e', 1), ('g', 2), ('l', 1), ('o', 2)]
当我加上 if i not in y[j]
这个过滤条件后,它却只返回了一个空列表 []。
有人能帮我指出我哪里出错了吗?
7 个回答
你的列表 y
总是空的。你根本没有进入循环 for j in range(len(y))
。
另外,你的代码写得不是很符合 Python 的风格。
在最新的Python 3和Python 2上都运行得很好。
def countItems(iter):
from collections import Counter
return sorted(Counter(iter).items())
我不太确定你期望的输出是什么,不过根据问题的描述,似乎你应该先对单词进行排序,这样才能得到字母的数量,按顺序排列。下面的代码可能会对你有帮助:
def countLetters(word):
letter = []
cnt = []
for c in sorted(word):
if c not in letter:
letter.append(c)
cnt.append(1)
else:
cnt[-1] += 1
return zip(letter, cnt)
print countLetters('hello')
这段代码会给你这样的结果:[('e', 1), ('h', 1), ('l', 2), ('o', 1)]
我觉得问题出在你的外层 for
循环上,因为你是在遍历单词中的每个字母。
如果这个单词里有某个字母出现了多次,比如 "bees"
,那么在遍历的时候,它会把 'e'
计算两次,因为 for
循环并不会区分字母是否唯一。你可以看看字符串迭代器,这可能会让你更明白。我不确定这能否解决你的问题,但这是我注意到的第一个点。
你可以试试这样的做法:
tally= {}
for s in check_string:
if tally.has_key(s):
tally[s] += 1
else:
tally[s] = 1
然后你就可以从那个字典中获取每个字母的计数。
如果你使用的是Python 2.7或更高版本,我推荐使用collections
模块里的Counter
。
>>> import collections
>>> s = 'a word and another word'
>>> c = collections.Counter(s)
>>> c
Counter({' ': 4, 'a': 3, 'd': 3, 'o': 3, 'r': 3, 'n': 2, 'w': 2, 'e': 1, 'h': 1, 't': 1})
在任何版本的Python中,你只需要多写一两行代码就能做到同样的事情:
>>> c = {}
>>> for i in s:
... c[i] = c.get(i, 0) + 1
这也可以帮助你检查自己的工作。
如果你想按字母顺序排序(上面的例子是按出现频率排序的),可以这样做:
>>> for letter, count in sorted(c.items()):
... print '{letter}: {count}'.format(letter=letter, count=count)
...
: 4
a: 3
d: 3
e: 1
h: 1
n: 2
o: 3
r: 3
t: 1
w: 2
或者你可以保持一个可以重复使用的字典格式:
>>> import pprint
>>> pprint.pprint(dict(c))
{' ': 4,
'a': 3,
'd': 3,
'e': 1,
'h': 1,
'n': 2,
'o': 3,
'r': 3,
't': 1,
'w': 2}
最后,如果你想把结果变成一个列表,可以这样做:
>>> pprint.pprint(sorted(c.items()))
[(' ', 4),
('a', 3),
('d', 3),
('e', 1),
('h', 1),
('n', 2),
('o', 3),
('r', 3),
('t', 1),
('w', 2)]