python

时间:2021-07-22
本文章向大家介绍python ,主要包括python 使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
# 给定字符串统计每个字母出现次数,并按照字母频率降序输出
 1 # 给定字符串统计每个字母出现次数,并按照字母频率降序输出
 2 def getKey(dic, value):
 3     if value not in dic.values():
 4         return None
 5     result = set()
 6     for key in dic:
 7         if dic[key]==value:
 8             result.add(key)
 9     return result
10 
11 def count_each_char_1(string):
12     res = {}
13     for i in string:
14         if i not in res:
15             res[i] = 1     # 将 键为i 的 加入字典
16         else:
17             res[i] += 1
18     return res
19 res = count_each_char_1('aaaaaennnabbbbsascd')
20 print(res)
21 b = len(res)
22 for i in range(b):
23     maxValue=max(res.values()) # 获取当前最大
24     result = getKey(res,maxValue)  # 获取键值
25     for j in result:
26         print(j,":",maxValue)
27     res.pop(j) # 删除对应键值
out:

{'a': 7, 'e': 1, 'n': 3, 'b': 4, 's': 2, 'c': 1, 'd': 1}
a : 7
b : 4
n : 3
s : 2
c : 1
d : 1
e : 1
d : 1
c : 1
d : 1


原文地址:https://www.cnblogs.com/ljh354114513/p/15045538.html