python中字典、字符串、列表的快速统计排序

Python中的collections模块可以对字典,字符串,列表进行快速的统计并排序

一、对列表进行统计排序

import collections
# 对列表进行统计
obj = collections.Counter(['a', 'a', 'a', 'b', 'b', 'c'])
print(obj)

结果为:

Counter({'a': 3, 'b': 2, 'c': 1})

二、对字符串进行统计排序

import collections
# 对字符串进行统计
obj = collections.Counter('aabbccccdddds')
print(obj)

结果:

Counter({'c': 4, 'd': 4, 'a': 2, 'b': 2, 's': 1})

三、对字典进行按值排序

from collections import OrderedDict
d ={'banana':3,'apple':4,'pear':1,'orange':2}
od = OrderedDict(sorted(d.items()))
print(od)

结果:

OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

猜你喜欢

转载自blog.csdn.net/a857553315/article/details/93774033
今日推荐