use*_*636 2 python counter dictionary list count
我必须编写一个函数,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
Run Code Online (Sandbox Code Playgroud)
我没先试过它 if i not in y[j]
countLetters("google")
Run Code Online (Sandbox Code Playgroud)
结果是
[('g', 2), ('o', 2), ('o', 2), ('g', 2), ('l', 1), ('e', 1)]
Run Code Online (Sandbox Code Playgroud)
当我想要的时候
[('e', 1), ('g', 2), ('l', 1), ('o', 2)]
Run Code Online (Sandbox Code Playgroud)
当我添加if i not in y[j]过滤器时,它只返回一个空列表[].
有人可以在这里指出我的错误吗?
如果您使用的是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})
Run Code Online (Sandbox Code Playgroud)
您可以在任何版本的Python中使用额外的一行或两行执行相同的操作:
>>> c = {}
>>> for i in s:
... c[i] = c.get(i, 0) + 1
Run Code Online (Sandbox Code Playgroud)
这对检查你的工作也很有用.
按字母顺序排序(以上按频率排序)
>>> 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
Run Code Online (Sandbox Code Playgroud)
或者保持一种可以作为dict重用的格式:
>>> 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}
Run Code Online (Sandbox Code Playgroud)
最后,将其作为列表:
>>> pprint.pprint(sorted(c.items()))
[(' ', 4),
('a', 3),
('d', 3),
('e', 1),
('h', 1),
('n', 2),
('o', 3),
('r', 3),
('t', 1),
('w', 2)]
Run Code Online (Sandbox Code Playgroud)