统计字符串中的字符数量用Counter函数
def __init__(*args, **kwds):
'''Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
'''
if not args:
raise TypeError("descriptor '__init__' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
super(Counter, self).__init__()
self.update(*args, **kwds)
示例:
#统计字符串中个字母的次数并排序
from collections import Counter
st = "1a,2b,3c,aa,bb,cc,22,33,11,ab,ac,bc"
counter = Counter(st) # 字符计数
counter_to_dict = dict(counter) # 返回值字典化
dict_change = {} # 空字典存储排序后的字典
for x in sorted(counter_to_dict.items(), key=None, reverse=True): # 降序
dict_change[x[0]] = x[1]
print(type(counter), counter)
print(type(counter_to_dict), counter_to_dict)
print(dict_change)
结果:
D:\mypy\venv\Scripts\python.exe D:/mypy/conuter.py
Counter({',': 11, 'a': 5, 'b': 5, 'c': 5, '1': 3, '2': 3, '3': 3})
{'1': 3, 'a': 5, ',': 11, '2': 3, 'b': 5, '3': 3, 'c': 5}
{'c': 5, 'b': 5, 'a': 5, '3': 3, '2': 3, '1': 3, ',': 11}
Process finished with exit code 0