根据计数的字母顺序进行排序

2024-09-27 00:16:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: keyinfromimportforvaluedefcounter
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').items(), key=lambda x: (-x[1], x[0])))
# [('g', 2), ('h', 2), ('o', 2), ('e', 1), ('l', 1)]

demo

以下是您可以做的:

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

相关问题 更多 >

    热门问题