Python 按字符串出现情况排序

Python 按字符串出现情况排序,python,Python,在python中,是否可以在字符串出现时计数字母并按字符排序 比如说, string = "Johnyjohny" output: {'J': 1, 'o': 2, 'h': 2, 'n': 2, 'y': 2, 'j': 1} 我可以数一数,也可以按字母顺序排序 def dictcode(str=""): str = "Johnyjohny" dict1 = dict((letter,str.count(lette

在python中,是否可以在字符串出现时计数字母并按字符排序

比如说,

string = "Johnyjohny"

output:
{'J': 1, 'o': 2, 'h': 2, 'n': 2, 'y': 2, 'j': 1}
我可以数一数,也可以按字母顺序排序

def dictcode(str=""):
    str = "Johnyjohny"
    dict1 = dict((letter,str.count(letter)) for letter in set(str))

    return dict1

print(dictcode())

字典没有真正的排序,因此不能真正“排序”。相反,您可以这样做:

sorted_dict = sorted(dictcode().items(), key=lambda x : x[1], reverse=True)
输出: [y',2',h',2',o',2',n',2',j',1',j',1]

它返回一个元组列表,但这应该没问题。

Hi,也许计数器可能会感兴趣