字符串字符统计

给定一个字符串,需要统计字符串中每个字符出现的次数,并按照出现频次从高到低排列。

方法一:

1
2
3
4
5
6
>>> s = 'hello, world'
>>> a = {k:s.count(k) for k in set(s.replace(' ',''))}
>>> a
{'l': 3, 'd': 1, ',': 1, 'o': 2, 'e': 1, 'w': 1, 'h': 1, 'r': 1}
>>> sorted(a.items(),key=lambda d: d[1], reverse=True) # 按照 value 排序
[('l', 3), ('o', 2), ('d', 1), ('r', 1), ('w', 1), ('h', 1), ('e', 1)]

方法二:

1
2
3
4
5
a = {}
for i in string:
if i not in a and i.isalpha():
a[i] = string.count(i)
sorted(a.items(),key=lambda d: d[1], reverse=True)
1
[('l', 3), ('o', 2), ('d', 1), ('r', 1), ('e', 1), ('h', 1), ('w', 1)]
觉得还不错?赞助一下~
0%