python - 如何通过函数按 ASCII 降序对单个字符串输出进行排序?

标签 python python-2.7 function sorting ascii

我有一串单词,我试图对每个字母表进行计数以获得单个字母的计数。但是,我想以 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/

相关文章:

python - NumPy - 在指定索引后插入一个零数组

python - 值错误 : index must be monotonic increasing or decreasing : Adding milliseconds

Python 错误 - int 对象没有属性

python - 从python中的日期字符串中提取年份

python - 如何调用嵌套函数?

python - 不显示存储在运行 flask 文件的模板文件夹中的 gif 图像

python - 为什么 Python argparse 中的 fromfile-prefix-chars 不起作用?

C# - 通过网络解决方案调用另一个程序中的函数

c++ - Eigen::vector ;在函数中使用 Eigen::Matrix3f 的值初始化 vector ,大于 4 个条目

javascript - JS无法调用函数