June 7 Python Review collections

Source: Internet
Author: User

Collections is a python built-in collection module that provides a number of useful collection classes.

Namedtuple

We know that we tuple can represent immutable collections, for example, two-dimensional coordinates of a point can be expressed as:

>>> p = (12)

However, (1, 2) it is difficult to see that this tuple is used to denote a coordinate.

Defining a class is a fuss, and then namedtuple it comes in handy:

 fromCollectionsImportNamedtuplepoint= Namedtuple (' Point', ['x','y'])
#Namedtuple constructs a class named Card with two attributes rank and suit
p = Point (1, 2)Print(p.x)Print(P.Y)
‘‘‘
Output: A" "

namedtupleis a function that creates a custom object and specifies the tuple tuple number of elements and an element that can be referenced by a property rather than an index tuple .

In this way, we namedtuple can easily define a data type, it has the invariant of tuple, and can be referenced according to the attribute, the use is very convenient.

You can verify that the Point object being created is tuple a seed class:

>>> isinstance(p, Point)True>>> isinstance(p, tuple)True

Similarly, if you want to represent a circle with coordinates and radii, you can also use the namedtuple definition:

# namedtuple(‘名称‘, [属性list]):Circle = namedtuple(‘Circle‘, [‘x‘‘y‘‘r‘])

Deque

listwhen using stored data, accessing elements by index is very fast, but inserting and deleting elements is very slow, because list it is linear, and when the data is large, insertions and deletions are inefficient.

Deque is a two-way list for efficient insert and delete operations, suitable for queues and stacks:

>>> fromimport deque>>> q = deque([‘a‘‘b‘‘c‘])>>> q.append(‘x‘)>>> q.appendleft(‘y‘)>>> qdeque([‘y‘‘a‘‘b‘‘c‘‘x‘])

dequeIn addition to implementing the and outside of the list append() pop() , support appendleft() and popleft() , in this way, can be very efficient to add or remove elements to the head.

Defaultdict

dictwhen used, if the referenced key does not exist, it will be thrown KeyError . If you want to return a default value when the key does not exist, you can use defaultdict :

>>> fromimport defaultdict>>> dd = defaultdict(lambda‘N/A‘)>>> dd[‘key1‘‘abc‘>>> dd[‘key1‘# key1存在‘abc‘>>> dd[‘key2‘# key2不存在,返回默认值‘N/A‘

Note The default value is returned by the calling function, and the function is passed in when the object is created defaultdict .

In addition to returning the default value when key does not exist, defaultdict the other behavior dict is exactly the same.

Ordereddict

dictwhen used, key is unordered. We were dict unable to determine the order of the keys when doing iterations.

If you want to keep the key in order, you can use OrderedDict :

>>> fromCollectionsImportOrdereddict>>>D = Dict ([(' A ',1), (' B ',2), (' C ',3)])>>>D# Dict's key is unordered.{' A ':1,' C ':3,' B ':2}>>>OD = Ordereddict ([(' A ',1), (' B ',2), (' C ',3)])>>>Od# Ordereddict's key is ordered.Ordereddict ([(' A ',1), (' B ',2), (' C ',3)])

Note that OrderedDict the keys are arranged in the order in which they are inserted, not the key itself:

>>> od = OrderedDict()>>> od[‘z‘1>>> od[‘y‘2>>> od[‘x‘3>>> # 按照插入的Key的顺序返回[‘z‘‘y‘‘x‘]

OrderedDictYou can implement a FIFO (first-in-one-out) dict, deleting the first added key when the capacity exceeds the limit:

  
 fromCollectionsImportordereddictclasslastupdatedordereddict (ordereddict):def __init__(self, capacity): Super (Lastupdatedordereddict, self).__init__() self._capacity=capacitydef __setitem__(self, Key, value): ContainsKey= 1ifKeyinchSelfElse0ifLen (self)-ContainsKey >=Self._capacity:last= Self.popitem (last=False)Print 'Remove:', lastifContainsKey:delSelf[key]Print 'Set:', (key, value)Else:            Print 'Add:', (key, Value) ordereddict.__setitem__(Self, key, value)

Counter

Counteris a simple counter, for example, the number of statistical characters that appear:

 fromCollectionsImportCounterc=Counter () dic=counter ('Programming') forChinch 'Programming': C[ch]= C[ch] + 1Print(DIC)Print("===========")Print(c)" "output: Counter ({' R ': 2, ' G ': 2, ' m ': 2, ' P ': 1, ' O ': 1, ' A ': 1, ' I ': 1, ' n ': 1}) ===========counter ({' R ': 2, ' G ': 2, ' m ': 2 , ' P ': 1, ' O ': 1, ' A ': 1, ' I ': 1, ' n ': 1}" "

CounterActually also dict a subclass, the above results can be seen, the characters ‘g‘ , ‘m‘ , ‘r‘ each appeared two times, the other characters appear once.

Summary

collectionsThe module provides some useful collection classes that can be selected as needed.

June 7 Python Review collections

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.