python==Counter,items,sorted

版权声明:转载请注明出处。 https://blog.csdn.net/Xin_101/article/details/83216068

本文介绍Counter、items和sorted使用。

  • Counter
    作用:统计字符出现的次数。
#源码
from collecitons import Counter
voc = 'hellothankyou'
voc1 = ['a','b','c','a','b','b']

counter = collections.Counter(voc)
counter1 = collections.Counter(voc1)

print(counter)
print(counter1)
#结果
Counter({'h': 2, 'l': 2, 'o': 2, 'e': 1, 't': 1, 'a': 1, 'n': 1, 'k': 1, 'y': 1, 'u': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
  • items
    作用:列表形式返回可遍历的值。
#源码
voc2 = {'name':'xin','sex':'male','job':'AI'}
output = voc2.items()
print(type(output))
print(output)
for k,v in output:
	print(k,v)
#结果
<class 'dict_items'>
dict_items([('name', 'xin'), ('sex', 'male'), ('job', 'AI')])
name xin
sex male
job AI
  • sorted
    作用:对所有可迭代的对象进行排序。
    sorted(iterable[,cmp[,key[,reverse]]])
    (1)iterable:可迭代对象
    (2)cmp:比较的函数,有两个参数,参数的值都是从可迭代的对象中取出,大于则返回1,小于返回-1,等于返回0
    (3)key:用于进行比较的元素
    (4)reverse:排序规则,reverse=True降序,reverse=False升序(默认)
voc = 'hellothankyou'
voc2 = [('a',3),('b',2),('c',1)]
output1 = sorted(voc)
#按第一个元素进行排序
output2 = sorted(voc2, key=lambda x:x[0])
#按第二个元素排序
output3 = sorted(voc2, key=lambda x:x[1])
print(output1)
print(output2)
print(output3)
#结果
['a', 'e', 'h', 'h', 'k', 'l', 'l', 'n', 'o', 'o', 't', 'u', 'y']
[('a', 3), ('b', 2), ('c', 1)]
[('c', 1), ('b', 2), ('a', 3)]


猜你喜欢

转载自blog.csdn.net/Xin_101/article/details/83216068