"Python Cookbook" "Data Structure and algorithm" 18. Map names to elements of a sequence

Source: Internet
Author: User

Problem: You want to access the element by name to reduce the dependency on the location in the structure

Solution: Use the named Tuple collections.namedtuple (). It is a factory method that returns a subclass of the standard tuple type in Python, gives it a type name and the corresponding field name , returns a class that can be instantiated, gives you a defined field name to pass in the value, and so on.

The primary purpose of a named tuple is to decouple the code from the location of the element it controls

>>> fromCollectionsImportNamedtuple>>> Sub=namedtuple ('Subscriber',['Addr','joined'])>>> Subscriber=sub ('[email protected]','2016-8-7')>>>Subscribersubscriber (Addr='[email protected]', joined='2016-8-7')>>>subscriber.addr'[email protected]'>>>subscriber.joined'2016-8-7'

Namedtuple instances are interchangeable with ordinary tuples and support operations supported by all common tuples, such as indexing and decomposition (unpacking).

>>> len (subscriber)2>>> addr,joined=subscriber>>> addr'  [email protected]'>>> joined'2016-8-7'

"Python Cookbook" "Data Structure and algorithm" 18. Map names to elements of a sequence

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.