python collections_Python collections使用

collections

collections为python提供了一些加强版的数据结构,当前有:

>>> collections.__all__

['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 'UserString', 'Counter', 'OrderedDict', 'ChainMap', 'Awaitable', 'Coroutine', 'AsyncIterable', 'AsyncIterator', 'AsyncGenerator', 'Hashable', 'Iterable', 'Iterator', 'Generator', 'Reversible', 'Sized', 'Container', 'Callable', 'Collection', 'Set', 'MutableSet', 'Mapping', 'MutableMapping', 'MappingView', 'KeysView', 'ItemsView', 'ValuesView', 'Sequence', 'MutableSequence', 'ByteString']

这里暂时把常见的,我用到的数据结构整理出来,之后有时间再继续添加。

1.OrderedDict

OrderedDict 可以理解为有序的dict,底层源码是通过双向链表来实现,每一个元素为一个map存储key-value。

>>> p = collections.OrderedDict()

>>> p["a"]=1

>>> p["b"]=2

>>> p["c"]=3

>>> print(p)

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

OrderedDict提供了下面的一些api。

>>> p.

p.clear( p.fromkeys( p.items( p.move_to_end( p.popitem( p.update(

p.copy( p.get( p.keys( p.pop( p.setdefault( p.values(

简单地试一下update,pop,move_to_end和clear

>>> keys=["apple", "banana", "cat"]

>>> value=[4, 5, 6]

# update

>>> p.update(zip(keys,value))

>>> p

OrderedDict([('a', 1), ('b', 2), ('c', 3), ('apple', 4), ('banana', 5), ('cat', 6)])

# pop

>>> p.pop('a')

1

>>> p

OrderedDict([('b', 2), ('c', 3), ('apple', 4), ('banana', 5), ('cat', 6)])

# move_to_end

>>> p.move_to_end('b')

>>> p

OrderedDict([('c', 3), ('apple', 4), ('banana', 5), ('cat', 6), ('b', 2)])

# del

>>> del(p['c'])

>>> p

OrderedDict([('apple', 4), ('banana', 5), ('cat', 6), ('b', 2)])

# clear

>>> p.clear()

>>> p

OrderedDict()

2.namedtuple

当tuple太长的时候,有时候就不知道数据的对应关系,namedtuple就是给tuple的元素命名。

>>> Point = namedtuple('Point', ['x', 'y'])

>>> Point.__doc__ # docstring for the new class

'Point(x, y)'

>>> p = Point(11, y=22) # instantiate with positional args or keywords

namedtuple既支持tupleindex的访问方式,也支持通过属性访问

>>> p[0] + p[1] # indexable like a plain tuple

33

>>> x, y = p # unpack like a regular tuple

>>> x, y

(11, 22)

>>> p.x + p.y # fields also accessible by name

33

namedtuple和dict的互转,严格说是与OrderedDict互转,因为_asdict返回的是一个OrderedDict

>>> d = p._asdict() # convert to a dictionary

>>> d

OrderedDict([('x', 11), ('y', 22)])

>>> Point(**d) # convert from a dictionary Point(x=11, y=22)

>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields

Point(x=100, y=22)

关于namedtuple的思考,我觉得大多数情况下,namedtuple都是可以用OrderedDict完美替换的,但是如果说我们需要一个OrderedDict模板的时候,像如下情况,namedtuple就更加有效率:

>>> a=Point(1,1)

>>> b=Point(2,2)

>>> a

Point(x=1, y=1)

>>> b

Point(x=2, y=2)

3.deque

deque是一个双向链表,针对list连续的数据结构插入和删除进行优化。提供以下的api:

>>> deque.

deque.append( deque.clear( deque.count( deque.extendleft( deque.insert( deque.mro( deque.popleft( deque.reverse(

deque.appendleft( deque.copy( deque.extend( deque.index( deque.maxlen deque.pop( deque.remove( deque.rotate(

简单体验一把rotate 和 reverse。

>>> a=deque(range(6))

>>> a

deque([0, 1, 2, 3, 4, 5])

>>> a.rotate()

>>> a

deque([5, 0, 1, 2, 3, 4])

>>> a.reverse()

>>> a

deque([4, 3, 2, 1, 0, 5])

4.defaultdict

defaultdict当修改未初始化的key-value时,会用默认值替换,其他功能与dict相同:

>>> a=defaultdict(list) # list's default value is []

>>> a["first"].append(1)

>>> a

defaultdict(, {'first': [1]})

>>> a["second"].append(1)

>>> a

defaultdict(, {'first': [1], 'second': [1]})

>>> b=defaultdict(int) # int's default value is 0

>>> b["a"] +=1

>>> b["b"] +=10

>>> b

同时初始化时,可以通过callback函数传入初始化值:

>>> c=defaultdict(lambda :1) # default value is 1

>>> c["c"] +=1

>>> c

defaultdict( at 0x101a25488>, {'c': 2})

5.Counter

Counter是dict的子类,所以操作同dict,在此基础上,又添加了most_common(),elements().

>>> from collections import Counter

>>> a=Counter("abca")

>>> a

Counter({'a': 2, 'b': 1, 'c': 1})

>>> a["a"]

2

>>> a.elements()

>>> sorted(a.elements())

['a', 'a', 'b', 'c']

>>> a.most_common(1)

[('a', 2)]

>>> a.most_common()

[('a', 2), ('b', 1), ('c', 1)]

小结

嗯,通过学习collections,我觉得自己的script可以写得更加pythonic,哈哈,希望明天会更好!Work by day, study by month, plan by year.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值