容器类型
类型 | 描述 |
---|---|
namedtuple | factory function for creating tuple subclasses with named fields |
deque | list-like container with fast appends and pops on either end |
ChainMap | dict-like class for creating a single view of multiple mappings |
Counter | dict subclass for counting hashable objects |
OrderedDict | dict subclass that remembers the order entries were added |
defaultdict | dict subclass that calls a factory function to supply missing values |
UserDict | wrapper around dictionary objects for easier dict subclassing |
UserList | wrapper around list objects for easier list subclassing |
UserString | wrapper around string objects for easier string subclassing |
namedtumple
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=11, y=22)
# p: Point(x=11, y=22)
# p[0](p.x): 11
# p[1](p.y): 22
deque
aa = deque([],5)
aa.extend([1,2,3,4,5,6])
# deque([2, 3, 4, 5, 6], maxlen=5)
aa.remove(2)
# deque([3, 4, 5, 6], maxlen=5)
aa.insert(1,'a')
# deque([3, 'a', 4, 5, 6], maxlen=5)
aa.rotate(n=1)
# deque([6, 3, 'a', 4, 5], maxlen=5)
aa.appendleft(1)
# deque([1, 6, 3, 'a', 4], maxlen=5)
ChainMap
d = ChainMap({'a': 'a'}, ['123'], ['a', 'b'], ['aa', 'bb'])
f = d.new_child({'f': 'f'})
# ChainMap({'f': 'f'}, {'a': 'a'}, ['123'], ['a', 'b'], ['aa', 'bb'])
d.maps[0]
# {'a': 'a'}
Counter
n = Counter('124133')
# Counter({'1': 2, '3': 2, '2': 1, '4': 1})
product = 1
for s in n.elements():
product *= int(s)
# product: 72
OrderedDict
d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# OrderedDict([('a', 1), ('b', 2), ('c', 3)])
d.move_to_end('a')
# OrderedDict([('b', 2), ('c', 3), ('a', 1)])
d.keys()
# odict_keys(['b', 'c', 'a'])
d.move_to_end('a', last=False)
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
defaultdict
aa = defaultdict(dict)
aa['a']['b'] = 'ok'
# defaultdict(<class 'dict'>, {'a': {'b': 'ok'}})
tree = lambda: defaultdict(tree)
aa = tree()
aa['a']['b']['c'] = "abc"
# defaultdict(<function <lambda> at 0x0000000002853048>, {'a': defaultdict(<function <lambda> at 0x0000000002853048>,{'b':defaultdict(<function <lambda> at 0x0000000002853048>, {'c': 'abc'})})})