首页 > 其他 > 详细

collections

时间:2020-10-30 10:11:14      阅读:20      评论:0      收藏:0      [点我收藏+]

1、namedtuple:生成可以使用名字来访问元素内容的tuple

第一个参数的元组的名字,第二个参数是元组中元素的[名字, 名字]

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p, p.x)

2、deque:双端队列,可以快速的从另外一侧追加和推出对象

from collections import deque
lst = deque([1, 2, 3, 4, 5])
lst.append(6)
lst.appendleft(0)
lst.pop()
lst.popleft()
print(lst)

栈:先进后出

队列:先进先出

lst = [0, 1, 2, 3, 4]
lst.append(5)
lst.pop(0)
print(lst)

3、Counter:计数器,主要用来统计元素的次数

str:

from collections import Counter
s = "1223334444555550000000000"
print(dict(Counter(s)))

list:

from collections import Counter
s = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
print(Counter(s))

tuple:

from collections import Counter
s = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
print(Counter(s))

4、OrderedDict:有序字典

5、defaultdict:带有默认值的字典

from collections import defaultdict
dic = defaultdict(list)
dic["k1"].append(1)
print(dic)

collections

原文:https://www.cnblogs.com/Ylinn/p/13900245.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!