How to count characters in a file and print them sorted alphanumerically

雨燕双飞 提交于 2019-11-29 16:55:24

Whenever dealing with counting, you can use collections.Counter here:

>>> from collections import Counter
>>> print sorted(Counter('xli uymgo fvsar jsb'.replace(' ', '')).most_common())
[('a', 1), ('b', 1), ('f', 1), ('g', 1), ('i', 1), ('j', 1), ('l', 1), ('m', 1), ('o', 1), ('r', 1), ('s', 2), ('u', 1), ('v', 1), ('x', 1), ('y', 1)]

If you can't import any modules, then you can append a to a list and then sort it:

new = []
for i in f:
    new.append(i + ' ' + str(f.count(i)) # Note that i is a string, so str() is unnecessary

Or, using a list comprehension:

new = [i + ' ' + str(f.count(i)) for i in f]

Finally, to sort it, just put sorted() around it. No extra parameters are needed because your outcome is alphabetical :).

Here's a oneliner without imports:

{s[i]: n for i, n in enumerate(map(s.count, s))}

And in alphabetical order (if the above is d):

for k in sorted(d): print k, d[k]

Or another version (oneliner alphabetical):

sorted(set([(s[i], n) for i, n in enumerate(map(s.count, s))]))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!