Python's Collections Module

Source: Internet
Author: User

Collections Module Knowledge Points
    • Counter class
    • Defaultdict class
    • Namedtuple class

In this experiment we will learn the Collections module. This module implements a number of good data structures that can help you solve a variety of practical problems.

>>> import collections

This is how to import this module, now let's take a look at some of these classes.

1. Counter

Counteris a dict subclass that helps hashable object counts. It is an unordered collection where the elements of the hashable object are stored as dictionary keys, their counts are stored as dictionary values, and the count can be any integer, including 0 and negative numbers.

We can view Counter the Help information in this way, in fact this information originates from the Counter document string ( collections.Counter.__doc__ ).

Let's look at an example where we look at the number of occurrences of certain words in Python's LICENSE file.

1.1. Counter Example
>>>From collectionsImport Counter>>>Import re>>> Path ='/usr/lib/python3.4/license.txt '>>> words = Re.findall (>>> Counter (words). Most_common (10) [( 80), ( ' or ', 78", ( ' 1 ', 66), ( ' of ', 61), ( ' to ', 50), (48), ( ' python ', 46), ( ' in ', 38), ( ' license ', 37), ( ' any ', 37)]              

The Counter object has a elements() method called, in which the sequence of elements returned is the same number of times as the count repeats, and the element order is unordered.

>>> c = Counter(a=4, b=2, c=0, d=-2)>>> list(c.elements())[‘a‘, ‘a‘, ‘a‘, ‘a‘, ‘b‘, ‘b‘]

most_common()The method returns the most common elements and their counts, in the order of the most common to least.

>>> Counter(‘abracadabra‘).most_common(3)[(‘a‘, 5), (‘r‘, 2), (‘b‘, 2)]
2. Defaultdict

defaultdictis a dict subclass of the built-in class that override a method and add a writable instance variable. The rest of the functionality is the same as the dictionary.

defaultdict()The first parameter provides the default_factory initial value of the property, the default value None , and the default_factory property value as the default data type for the dictionary. All remaining parameters are the same as the dictionary construction method, including the keyword parameters.

The same functionality is used defaultdict faster than using dict.setdefault methods.

Defaultdict use case

>>>From collectionsImport Defaultdict>>> s = [(' Yellow ',1), ( ' Blue ', 2), ( ' yellow ', 3), ( ' Blue ', 4), ( ' Red ', 1)] >>> d = defaultdict (list) >>> for K, v in s: ... d[k].append (v) ... >>> d.items () dict_items ([2, Span class= "Hljs-number" >4]), ( ' Red ', [1]), ( Yellow", [1, 3])])      

As you can see in the example, defaultdict it automatically creates an empty list, even if the object does not already have a key .

3. Namedtuple

Named tuples help give meaning to each tuple's location, and make our code more readable and self-documenting. You can use named tuples anywhere you use tuples. In the example we will create a named tuple to show that the information is saved for each location in the tuple.

>>>From collectionsImport Namedtuple>>> point = Namedtuple (' Point ', [' x ', ' y ']) # define named tuples >>> p = Point (ten, y=) # Create an object >>> ppoint (x=, y=)  >>> p.x + p.y>>> p[0] + p[1] # access elements like normal tuples >>> x, y = P c18># pack >>> x>>> y       
Summarize

In this experiment we used some of the data structures in collections, and maybe you don't use them at the moment, but hopefully you'll think of them later when you need them:-)

Knowledge points
    • Counter class
    • Defaultdict class
    • Namedtuple class

In this experiment we will learn the Collections module. This module implements a number of good data structures that can help you solve a variety of practical problems.

>>> import collections

This is how to import this module, now let's take a look at some of these classes.

1. Counter

Counteris a dict subclass that helps hashable object counts. It is an unordered collection where the elements of the hashable object are stored as dictionary keys, their counts are stored as dictionary values, and the count can be any integer, including 0 and negative numbers.

We can view Counter the Help information in this way, in fact this information originates from the Counter document string ( collections.Counter.__doc__ ).

Let's look at an example where we look at the number of occurrences of certain words in Python's LICENSE file.

1.1. Counter Example
>>>From collectionsImport Counter>>>Import re>>> Path ='/usr/lib/python3.4/license.txt '>>> words = Re.findall (>>> Counter (words). Most_common (10) [( 80), ( ' or ', 78", ( ' 1 ', 66), ( ' of ', 61), ( ' to ', 50), (48), ( ' python ', 46), ( ' in ', 38), ( ' license ', 37), ( ' any ', 37)]              

The Counter object has a elements() method called, in which the sequence of elements returned is the same number of times as the count repeats, and the element order is unordered.

>>> c = Counter(a=4, b=2, c=0, d=-2)>>> list(c.elements())[‘a‘, ‘a‘, ‘a‘, ‘a‘, ‘b‘, ‘b‘]

most_common()The method returns the most common elements and their counts, in the order of the most common to least.

>>> Counter(‘abracadabra‘).most_common(3)[(‘a‘, 5), (‘r‘, 2), (‘b‘, 2)]
2. Defaultdict

defaultdictis a dict subclass of the built-in class that override a method and add a writable instance variable. The rest of the functionality is the same as the dictionary.

defaultdict()The first parameter provides the default_factory initial value of the property, the default value None , and the default_factory property value as the default data type for the dictionary. All remaining parameters are the same as the dictionary construction method, including the keyword parameters.

The same functionality is used defaultdict faster than using dict.setdefault methods.

Defaultdict use case

>>>From collectionsImport Defaultdict>>> s = [(' Yellow ',1), ( ' Blue ', 2), ( ' yellow ', 3), ( ' Blue ', 4), ( ' Red ', 1)] >>> d = defaultdict (list) >>> for K, v in s: ... d[k].append (v) ... >>> d.items () dict_items ([2, Span class= "Hljs-number" >4]), ( ' Red ', [1]), ( Yellow", [1, 3])])      

As you can see in the example, defaultdict it automatically creates an empty list, even if the object does not already have a key .

3. Namedtuple

Named tuples help give meaning to each tuple's location, and make our code more readable and self-documenting. You can use named tuples anywhere you use tuples. In the example we will create a named tuple to show that the information is saved for each location in the tuple.

>>>From collectionsImport Namedtuple>>> point = Namedtuple (' Point ', [' x ', ' y ']) # define named tuples >>> p = Point (ten, y=) # Create an object >>> ppoint (x=, y=)  >>> p.x + p.y>>> p[0] + p[1] # access elements like normal tuples >>> x, y = P c18># pack >>> x>>> y       
Summarize

In this experiment we used some of the data structures in collections, and maybe you don't use them at the moment, but hopefully you'll think of them later when you need them:-)

Python's Collections Module

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.