Python:collections.nametuple ()--mapping names to sequence elements

Source: Internet
Author: User

Questions: access the list or elements in a tuple by subscript

Answer: Collections.namedtuple () solves this problem by using a tuple object

This function is actually a factory method that returns a subclass of the standard tuple type in Python, needs to pass a type name and field to it, and then it returns a class that initializes a class that passes values for the defined fields.

EG1:

1.

>>> from collections Import Namedtuple
>>> subscriber = namedtuple (' subscriber ', [' addr ', ' joined '])
>>> Sub = subscriber (' [email protected] ', ' 2012-10-19 ')
>>> Sub
Subscriber (addr= ' [email protected] ', joined= ' 2012-10-19 ')
>>> sub.addr
' [Email protected] '
>>> sub.joined
' 2012-10-19 '

2. Support Index and decompression


>>> addr, joined = Sub
>>> Addr
' [Email protected] '
>>> joined
' 2012-10-19 '

EG2:

1. One use of named tuples freed from subscript operation

>>>from Collections Import Namedtuple
>>>stock = namedtuple (' Stock ', [' name ', ' shares ', ' price '])
>>>def Compute_cost (Records):
... Total = 0.0
... for rec in records:
... s = Stock (*rec)
... Total + = S.shares * S.Price
.. return Total

2. Another use of named tuples is as a substitute for dictionaries.

Dictionary storage requires more memory space, and if you need to build a very large data structure that contains a dictionary, it is more efficient to use tuples, and it is important to note that named tuples cannot be changed

>>> s = Stock (' ACME ', 100, 123.45)
>>> s
Stock (name= ' ACME ', shares=100, price=123.45)
>>> S.shares = 75
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror:can ' t set attribute

If you really need to change the properties of a named tuple, you can use the _replace () method of the named tuple instance, which creates a completely new named tuple and replaces the corresponding field with the new value

>>> s = s._replace (shares=75)
>>> s
Stock (name= ' ACME ', shares=75, price=123.45)

It is a very convenient way to populate the data. You can create a prototype tuple that contains default values , and then use the Replace () method to create a new instance of the value that has been updated. For example:
>>>from Collections Import Namedtuple
>>>stock = namedtuple (' Stock ', [' name ', ' shares ', ' price ', ' Date ', ' time ')
Stock_prototype = Stock ("', 0, 0.0, none, none)
>>>def Dict_to_stock (s):
... return stock_prototype._replace (**s)


Here's how it's used:
>>> a = {' name ': ' ACME ', ' shares ': +, ' price ': 123.45}
>>> Dict_to_stock (a)
Stock (name= ' ACME ', shares=100, price=123.45, Date=none, Time=none)
>>> B = {' name ': ' ACME ', ' shares ': +, ' price ': 123.45, ' date ': ' 12/17/2012 '}
>>> Dict_to_stock (b)
Stock (name= ' ACME ', shares=100, price=123.45, date= ' 12/17/2012 ', Time=none)

If the goal is to define an efficient data structure that needs to update many instance properties, named tuples are not the best choice, consider defining a class for a __slots__ method

Python:collections.nametuple ()--mapping names to sequence elements

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.