python 内置模块:collections

设置坐标:namedtuple

格式:

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

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

运行结果:

1
2 0
True

双向队列:deque

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

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

运行结果:

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

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

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

运行结果:

abc
N/A

顺序排列dist: OrderedDict

from collections import OrderedDict
d = 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 Counter
 
c = 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})

 

你可能感兴趣的