Python standard library notes (4)-collections module, pythoncollections

Source: Internet
Author: User
Tags iterable

Python standard library notes (4)-collections module, pythoncollections

This module provides several very useful Python container types

1. Container
Name Function Description
OrderedDict Dict that maintains the key Insertion Sequence
Namedtuple Generate a tuple subclass that can access element content by name
Counter Counter, mainly used to count
Deque Similar to a list container, you can quickly add or delete elements in the queue header and tail.
Defaultdict Child class of dict, dictionary with default value
2. OrderedDict

  OrderedDictSimilar to a normal dictionary, it only remembers the sequence of element insertion. When it is iterated, it is returned according to the insertion order.

  • Compared with a normal dictionary, it is "ordered" (the order of insertion ).
From collections import OrderedDictdict1 = dict () # common dictionary dict1 ['apple'] = 2dict1 ['banana '] = 1dict1 ['Orange'] = 3dict2 = OrderedDict () # ordered dictionary dict2 ['apple'] = 2dict2 ['bana'] = 1dict2 ['Orange '] = 3for key, value in dict1.items (): print 'key :', key, 'value: ', valuefor key, value in dict2.items (): print 'key:', key, 'value: ', value
# ---- Output result ----- # normal dictionary key: orange value: 3key: apple value: 2key: banana value: 1 # ordered dictionary key: apple value: 2key: banana value: 1key: orange value: 3
  • If you rewrite an existing key, the original sequence remains unchanged. If you delete an element and insert it again, it will be at the end.
From collections import OrderedDictdict2 = OrderedDict () dict2 ['apple'] = 2dict2 ['banana '] = 1dict2 ['Orange'] = 3 # directly rewrite the value of apple, order unchanged dict2 ['apple'] = 0 # Delete and re-write banana, order change dict2.pop ('bana') dict2 ['bana'] = 1 print dict2
# ---- Output result ----- OrderedDict ([('apple', 0), ('Orange ', 3), ('banana', 1)])
  • You can use the sorting function to convert a common dictionary into OrderedDict.
from collections import OrderedDictd = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}order_d = OrderedDict(sorted(d.items(), key=lambda t: t[1]))for key, value in order_d.items():    print 'key:', key, ' value:', value
# ---- Output result ----- key: pear value: 1key: orange value: 2key: banana value: 3key: apple value: 4
3. namedtuple

Namedtuple is the named tuple. Generally, tuple is like this (item1, item2, item3 ,...), All items can only be accessed through index, but there is no clear name, And namedtuple is to name these items in advance, which will be convenient to access in the future.

From collections import namedtuple # defines a namedtuple-type User and includes the name, sex, and age attributes. User = namedtuple ('user', ['name', 'sex', 'age']) # create a User object user1 = User (name = 'name1 ', sex = 'male', age = 18) # You can use a list to create a User object. Note that you must use the "_ make" method user2 = User. _ make (['name2', 'male', 21]) print 'user1: ', user1 # obtain the property print 'name:', user1.name, 'sex: 'using the DoT number :', user1.sex, 'Age: ', user1.age # converts a User object to a dictionary. Use "_ asdict" print 'user1. _ asdict (): ', user1. _ asdict () # convert the dictionary to namedtuplename_dict = {'name': 'name3', 'sex': 'male', 'age ': 20} print 'dict2namedtuple: ', User (** name_dict) # Modify Object Attributes. Use the "_ replace" method to print 'replace :', user1. _ replace (age = 22)
# ---- Output result ----- user1: User (name = 'name1', sex = 'male', age = 18) name: name1 sex: male age: 18user1. _ asdict (): OrderedDict ([('name', 'name1'), ('sex', 'male'), ('age', 18)]) dict2namedtuple: user (name = 'name3', sex = 'male', age = 20) replace: User (name = 'name1', sex = 'male', age = 22)
4. Counter

The Counter class is used to track the number of occurrences of a value. It is an unordered container type, which is stored in the form of dictionary key-value pairs, where elements are used as keys and Their counts are used as values.

  • Counter can be created using the following methods:
From collections import Counterprint Counter ('aabbcccd') # create a print Counter (['A ', 'C']) # create print Counter ({'A': 4, 'B': 2}) from an iterable object (list, tuple, dict, String, etc }) # create print Counter (a = 4, B = 2) from a dictionary object # create from a group of key-value pairs
# ---- Output result ----- Counter ({'C': 3, 'A': 2, 'B': 2, 'D': 1}) Counter ({'A ': 2, 'C': 1}) Counter ({'A': 4, 'B': 2}) Counter ({'A': 4, 'B ': 2 })
  • The counting time of the retrieved element is similar to that of dict. If the key does not exist, 0 is returned instead of KeyError.
>>> c = Counter("acda")>>> c["a"]2>>> c["h"]0
  • You can use update and subtract to update (increase and decrease) the counter)
From collections import Counterc = Counter ('aaabbc') print 'C: ', cc. update ("abc") print 'C. update ("abc"): ', c # You can use another iterable object update to pass in a Counter Object c. subtract ("abc") print 'C. subtract ("abc"): ', c # A Counter object can be passed in with another iterable object subtract.
# ---- Output result ----- c: Counter ({'A': 3, 'B': 2, 'C': 1}) c. update ("abc"): Counter ({'A': 4, 'B': 3, 'C': 2}) c. subtract ("abc"): Counter ({'A': 3, 'B': 2, 'C': 1 })
  • Returns the top n elements of the count.
from collections import Counterc = Counter('aaaabbcccddeeffg')print c.most_common(3)
# ---- Output result ----- [('A', 4), ('C', 3), ('B', 2)]
  • Counter also supports a few mathematical operations +,-, &, and |
From collections import Counter = Counter (a = 3, B = 1) B = Counter (a = 1, B = 1) print 'a + B :', a + B # Addition, Count addition print 'a-B: ', a-B # subtraction, Count subtraction print' B-:', b-a # Only keep positive count print 'a & B: ', a & B # intersection print 'a | B:', a | B # Union
# ---- Output result ----- a + B: Counter ({'A': 4, 'B': 2}) a-B: Counter ({'A': 2 }) b-a: Counter () a & B: Counter ({'A': 1, 'B': 1}) a | B: Counter ({'A': 3, 'B': 1 })
5. deque

Deque is a dual-end queue, which is a data structure of the queue and stack nature. It is suitable for adding and deleting at both ends, similar to the container of the sequence.

  • Common Methods
From collections import dequed = deque ([]) # create an empty dual-queue d. append (item) # Add the project itemd to the right (end) of d. appendleft (item) # Add the project itemd from the left (start) of d. clear () # clear the queue, that is, delete all projects in d. extend (iterable) # add all project d in iterable to the right (end) of d. extendleft (item) # add all items in item d to the left (start) of d. pop () # Delete and return the last (rightmost) project in d. If d is null, IndexErrord. popleft () # is deleted and the first (leftmost) project in d is returned. If d is null, IndexErrord is thrown. rotate (n = 1) # rotate d to the right n steps (if n <0, then rotate to the left) d. count (n) # count the number of elements in the queue. n indicates the statistical Element d. remove (n) # Delete the specified value d from the queue. reverse () # flipped queue
6. defaultdict

When using dict, if the referenced Key does not exist, it will throwKeyError. If you want to return a default value when the key does not exist, you can use defaultdict

  • For example, to count the frequency of occurrence of each word in a string
From collections import defadicdicts = 'ilikepython '# use the normal dictionary frequencies ={} for each in s: frequencies [each] + = 1 # use the normal dictionary frequencie = defaultdict (int) for each in s: frequencie [each] + = 1

The first code will throwKeyErrorAnd use defaultdict. Defaultdict can also be initialized using a function as a parameter:

>>> from collections import defaultdict>>> d = defaultdict(lambda : 0)>>> d['0']0

Related Article

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.