python中的Counter

统计字符串中的字符数量用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
<class 'collections.Counter'> Counter({',': 11, 'a': 5, 'b': 5, 'c': 5, '1': 3, '2': 3, '3': 3})
<class 'dict'> {'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

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值