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

时间:2018-09-26 02:40:41

标签: python python-2.7 function sorting ascii

我有一个单词字符串,我试图对每个字母进行计数以获得单独的字母计数。但是,我想按降序对它们进行ASCII排序。无论如何,这是在下面修改我的功能,以便我可以获得所需的输出吗?打印count(word1).sort()也不起作用,因为无法在单个str中执行排序。

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降序计数。

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如果要按ASCII降序排列字母,可以使用chrsorted函数。

word_dict = {...} # your current set of counts

for letter in sorted(word_dict.keys(), key=chr):
    print("%s: %d" % (letter, word_dict[letter]))

这应该适合您的用例。

答案 2 :(得分:0)

排序和计数应该可以解决问题

print(' '.join(sorted(['{}:{}'.format(i, w.count(i)) for i in w], reverse=True)))
v:1 t:1 s:1 o:1 i:1 e:1 a:1 L:1 C:1

答案 3 :(得分:0)

您尝试使用sorted($ your_list,reverse = True)吗?

例如:

>>> b
['aa', 'BB', 'bb', 'zz', 'CC']
>>> sorted(b,reverse=True)
['zz', 'bb', 'aa', 'CC', 'BB']
>>>

sorted(reverse=True)可以按ASCII降序输出列表b。