可使用collection模块中的Counter函数对可迭代对象计数 from collections import Counter
l=list('shfajsdas') #将可迭代对象字符串转化为list
l
['s', 'h', 'f', 'a', 'j', 's', 'd', 'a', 's']
c=Counter(l) #利用Counter函数对列表计数
c #返回Counter对象
Counter({'s': 3, 'a': 2, 'd': 1, 'h': 1, 'j': 1, 'f': 1})
list(c) #获取无重复key组成的list
['d', 'h', 'a', 's', 'j', 'f']
c.elements()
<itertools.chain object at 0x1031486d8>
list(c.elements()) #获取所有的key
['d', 'h', 'a', 'a', 's', 's', 's', 'j', 'f']
c.most_common() #按照次数大小输出 列表嵌套元组
[('s', 3), ('a', 2), ('d', 1), ('h', 1), ('j', 1), ('f', 1)]
c.most_common(2) #输出出现最多次数的元素和出现次数 返回列表
[('s', 3), ('a', 2)]
sorted(c.most_common(),key=lambda x :x[0]) #排序 和字典排序类似
[('a', 2), ('d', 1), ('f', 1), ('h', 1), ('j', 1), ('s', 3)]
#这样是输出key 和字典类似 字典应该数d.items()
sorted(c,key=lambda x :x[0])
['a', 'd', 'f', 'h', 'j', 's']
#字典
c={'a':3,'b':4}
list(c)
['b', 'a']
sorted(c,key=lambda x :x[0])
['a', 'b']
for i in c等价于for i in c.keys()
#应该是
sorted(c.items(),key=lambda x :x[0])
参考文档: