每当进行计数时,您都可以
collections.Counter在这里使用:
>>> 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)]如果您无法导入任何模块,则可以追加
a到列表中然后对其进行排序:
new = []for i in f: new.append(i + ' ' + str(f.count(i)) # Note that i is a string, so str() is unnecessary
或者,使用列表推导:
new = [i + ' ' + str(f.count(i)) for i in f]
最后,要对其进行排序,只需将
sorted()其放在周围即可。不需要额外的参数,因为您的结果是按字母顺序排列的:)。



