Python-collections Module

Source: Internet
Author: User

The following classes are provided in collections: [' deque ', ' defaultdict ', ' namedtuple ', ' userdict ', ' userlist ', ' userstring ', ' Counter ', ' Ordereddict ', ' Chainmap ']

1.namedtuple (): Generates a tuple subclass that can access the content of an element by using a name
2.deque: Double-ended queue to quickly append and eject objects from the other side
3.Counter: Counter, mainly used to count
4.OrderedDict: Ordered Dictionary
5.defaultdict: Dictionary with default values

Reference Blog: http://www.cnblogs.com/liupengpengg/p/5593273.html

Default Dictionary

You can specify the type of values in the dictionary

For example: Place a number greater than 55 in [11,22,33,44,55,66,77,88,99] in ' k1 ' and drizzle equals 55 in ' K2 '.

From collections Import Defaultdict

V=[11,22,33,44,55,66,77,88,99]

Dic=defaultdict (list)

For I in V:

If I >55:

dic[' K1 '].append (i)

Else

dic[' K2 '].append (i)

Print (DIC)

Results: defaultdict (<class ' list '), {' K2 ': [One, one, one, one, one], ' K1 ': [66, 77, 88, 99]})

Can name a tuple

renaming does not mean that elements in a tuple can be modified, but that each element in a tuple can be assigned a code name that can later be used to find the element, rather than by index. Note: To use this class we need to create the class first,

Example: Remove values from tuples in X, Y, Z

From collections Import Namedtuple

Point=namedtuple (' point ', [' X ', ' y ', ' z '])

A=point (11,22,33)

Print (A.X,A.Y,A.Z)

Results: 11 22 33

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