Python collections

容器类型
类型描述
namedtuplefactory function for creating tuple subclasses with named fields
dequelist-like container with fast appends and pops on either end
ChainMapdict-like class for creating a single view of multiple mappings
Counterdict subclass for counting hashable objects
OrderedDictdict subclass that remembers the order entries were added
defaultdictdict subclass that calls a factory function to supply missing values
UserDictwrapper around dictionary objects for easier dict subclassing
UserListwrapper around list objects for easier list subclassing
UserStringwrapper 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'})})})

转载于:https://my.oschina.net/redhands/blog/3009310

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值