提问者:小点点

根据计数的字母顺序排序


from collections import *
def compress(s):
    res = Counter(s)

    for key,value in res.items():
        print(key, value)

compress("hhgoogle")

输出:

h 2
g 2
o 2
l 1
e 1

如何根据计数按字母顺序排序,即:

所需输出:

g 2
h 2
o 2
e 1
l 1

共3个答案

匿名用户

首先按字母顺序排序,然后对出现的情况进行排序。 连接仅仅是以您所描述的格式输出它。

from collections import *
def compress(s):
    res= Counter(s)
    alphabetic_res = sorted(res.most_common(), key=lambda tup: tup[0])
    final_res = sorted(alphabetic_res, key=lambda tup: tup[1], reverse=True)
    print("\n".join("%s,%s" % tup for tup in final_res))

compress("hhgoogle")

OUT: g,2
     h,2
     o,2
     e,1
     l,1

匿名用户

您可以使用:

from collections import *

print(sorted(Counter('hhgoogle').most_common(), key=lambda x: (-x[1], x[0])))
# [('g', 2), ('h', 2), ('o', 2), ('e', 1), ('l', 1)]

演示

匿名用户

下面是您可以做的:

from collections import *
def compress(s):
    res= Counter(s)
    l1 = sorted(res.most_common(), key=lambda t: t[0])
    l2 = sorted(l1, key=lambda t: t[1], reverse=True)
    print('\n'.join([f"{t[0]} {t[1]}" for t in l2]))
compress("hhgoogle")

输出:

g 2
h 2
o 2
e 1
l 1