我有一串单词,我试图对每个字母表进行计数以获得单个字母的计数。但是,我想以 ASCII 降序对它们进行排序。无论如何,可以修改下面的函数以便我可以获得所需的输出吗? Print count(word1).sort() 也不起作用,因为无法在单个字符串中执行排序。
word1 = iLoveCats
def count(i):
word2 = Counter(i).most_common()
return " ".join("{}:{}".format(a, b) for a, b in word2)
print count(word1)
当前输出:
a:1 C:1 e:1 i:1 L:1 o:1 s:1 t:1 v:1
期望的输出: 按 ASCII 降序计数。
最佳答案
map
:
def count(i):
word2 = map(lambda x: map(str,x),Counter(i).items())
return " ".join(sorted(map(':'.join,word2),reverse=True))
或者理解:
def count(i):
word2 = Counter(i).items()
return " ".join(sorted(['{0}:{1}'.format(*i) for i in word2],reverse=True))
现在:
print count(word1)
两者均重现:
v:1 t:1 s:1 o:1 i:1 e:1 a:1 L:1 C:1
关于python - 如何通过函数按 ASCII 降序对单个字符串输出进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509190/