我是Python初学者,我正在尝试解决一些有关列表的问题。我被一个问题困住了,无法解决:
Write a function
countLetters(word)
that takes in a word as argument and returns a list that counts the number of times each letter appears. The letters must be sorted in alphabetical order.Ex:
>>> countLetters('google') [('e', 1), ('g', 2), ('l', 1), ('o', 2)]
我无法计算每个字符的出现次数。对于排序,我使用 sorted(list)
,并且还使用 dictionary(items functions)
来实现这种输出格式(列表元组)。但我无法将所有这些事情联系起来。
最佳答案
使用套装!
m = "google"
u = set(m)
sorted([(l, m.count(l)) for l in u])
>>> [('e', 1), ('g', 2), ('l', 1), ('o', 2)]
关于python - PySchool-列表(主题 6-22),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7678825/