热门IT资讯网

python 内置模块:collections

发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,设置坐标:namedtuple格式:变量名 = namedtuple(任意名,list)from collections import namedtuplePoint = namedtuple('po

设置坐标:namedtuple

格式:

变量名 = namedtuple(任意名,list)

from collections import namedtuplePoint = namedtuple('point', ['x', 'y', 'z'])p = Point(1,2,0)print(p.x)print(p.y, p.z)print(isinstance(p, tuple))

运行结果:

12 0True


双向队列:deque

https://docs.python.org/2.7/library/collections.html?highlight=deque#collections.deque

from collections import dequeq = deque(['a', 'b', 'c'])q.append('x')       #尾插q.appendleft('y')   #头插print(q)

运行结果:

deque(['y', 'a', 'b', 'c', 'x'])


默认字典:defaultdict, 如果没有该key值,默认输出指定值。

from collections import defaultdictdd = defaultdict(lambda: 'N/A')dd['key1'] = 'abc'print (dd['key1']) # key1存在print (dd['key2'])

运行结果:

abcN/A


顺序排列dist: OrderedDict

from collections import OrderedDictd = dict([('a', 1), ('b', 2), ('c', 3)])n = {'a':1, 'b':2, 'c':3}print (d) # dict的Key是无序的print (n) # dict的Key是无序的od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])print (od)# OrderedDict的Key是有序的

运行结果:

{'c': 3, 'b': 2, 'a': 1}{'c': 3, 'b': 2, 'a': 1}OrderedDict([('a', 1), ('b', 2), ('c', 3)])


计算数目:Counter

from collections import Counterc = Counter()for ch in 'programming':    c[ch] = c[ch] + 1    print(c)print(c)

运行结果:

Counter({'p': 1})Counter({'r': 1, 'p': 1})Counter({'r': 1, 'o': 1, 'p': 1})Counter({'r': 1, 'o': 1, 'p': 1, 'g': 1})Counter({'r': 2, 'o': 1, 'p': 1, 'g': 1})Counter({'r': 2, 'o': 1, 'p': 1, 'g': 1, 'a': 1})Counter({'r': 2, 'o': 1, 'p': 1, 'g': 1, 'a': 1, 'm': 1})Counter({'r': 2, 'm': 2, 'o': 1, 'p': 1, 'g': 1, 'a': 1})Counter({'r': 2, 'm': 2, 'o': 1, 'i': 1, 'p': 1, 'g': 1, 'a': 1})Counter({'r': 2, 'm': 2, 'o': 1, 'i': 1, 'n': 1, 'p': 1, 'g': 1, 'a': 1})Counter({'r': 2, 'g': 2, 'm': 2, 'o': 1, 'i': 1, 'n': 1, 'p': 1, 'a': 1})Counter({'r': 2, 'g': 2, 'm': 2, 'o': 1, 'i': 1, 'n': 1, 'p': 1, 'a': 1})



0