码迷,mamicode.com
首页 > 编程语言 > 详细

Python collections使用

时间:2020-02-13 22:37:56      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:cal   命名   access   byte   元素   targe   await   item   pre   

 

作者:大雄good
链接:https://www.jianshu.com/p/f2a429aa5963

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(

简单地试一下updatepopmove_to_endclear

>>> 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

namedtupledict的互转,严格说是与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(

简单体验一把rotatereverse

>>> 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(<class list>, {first: [1]})
>>> a["second"].append(1)
>>> a
defaultdict(<class list>, {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(<function <lambda> at 0x101a25488>, {c: 2})

 

5.Counter

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

>>> from collections import Counter
>>> a=Counter("abca")
>>> a
Counter({a: 2, b: 1, c: 1})
>>> a["a"]
2
>>> a.elements()
<itertools.chain object at 0x10190ed30>
>>> sorted(a.elements())
[a, a, b, c]
>>> a.most_common(1)
[(a, 2)]
>>> a.most_common()
[(a, 2), (b, 1), (c, 1)]

 

Python collections使用

标签:cal   命名   access   byte   元素   targe   await   item   pre   

原文地址:https://www.cnblogs.com/-wenli/p/12305543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!