Python namedtuple (named tuples)

Source: Internet
Author: User
Tags iterable wrapper python namedtuple

Collections Module Basic Introduction

Collections provides several optional data types on top of the common container dict,list,set and tuple

namedtuple() Factory function for creating tuple subclasses with named fields
deque List-like container with Fast appends and POPs on either end
ChainMap Dict-like class for creating a single view of multiple mappings
Counter Dict Subclass for Counting hashable objects
OrderedDict Dict subclass that remembers the order entries were added
defaultdict Dict subclass that calls a factory function to supply missing values
UserDict Wrapper around Dictionary objects for easier dict subclassing
UserList Wrapper around list objects for easier list subclassing
UserString Wrapper around string objects for easier string subclassing

Namedtuple ()

A tuple is similar to an array and can only be accessed through the following table. Using Namedtuple, each element has its own name and the meaning of the data is at a glance.

In [22]: fromCollectionsImportNamedtuplein [[]: Point = Namedtuple (' Point', ['x','y']) in []: p = point (one, y=22) in []: p[0] + p[1]out[25]: 33In [26]: p.xout[26]: 11In [27]: p.yout[27]: 22In [28]: pout[(): Point (x=11, y=22) in []: x, y =PIn [30]: xout[30]: 11

Named tuples also have three additional methods, two properties

somenamedtuple. Classmethod _make (iterable)

Class method that is makes a new instance from an existing sequence or iterable.

Create a new instance from an already existing sequence or an iterative object

 in [1]: from  collections import   Namedtuplein [ 2]: Point = Namedtuple ( " point   ", ["  x   ", "  y   ", "  z   " ]) in [ 3] : t = [1, 2, 3]in [ 4]: P = Point._make (t) in [ 5 Span style= "COLOR: #000000" >]: pout[ 5]: Point (X=1, y=2, z=3) 

somenamedtuple._asdict()

Return a new OrderedDict which maps field names to their corresponding values:

Returns a new ordereddict, with field names as key, field names corresponding value as values.

In [16]: fromCollectionsImportNamedtuplein [+]: Point = Namedtuple (' Point', ['x','y','Z']) in []: t = [1, 2, 3]in []: p =Point._make (t) in [20]: pout[]: Point (X=1, y=2, z=3) in []: D =p._asdict () in [(a): D.get ('x') out[22]: 1In [23]: dout[]: Ordereddict ([('x', 1), ('y', 2), ('Z', 3)])

somenamedtuple._replace(Kwargs)

Return a new instance of the named tuple replacing specified fields with new values:

Returns a new instance of a named tuple that replaces the specified field with a new value.

In [24]: fromCollectionsImportNamedtuplein []: Point = Namedtuple (' Point', ['x','y','Z']) in [+]: t = [1, 2, 3]in [+]: p =Point._make (t) in [28]: pout[(): Point (X=1, y=2, z=3) in []: P._replace (z=4) out[: Point (X=1, y=2, z=4) in [30]: p.zout[30]: 3In [+]: p = p._replace (z=4) in [33]: p.zout[33]: 4In [34]: pout[: Point (X=1, y=2, z=4)

somenamedtuple._fields

Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.

List of field names

in [+]: p._fieldsout[]: ('x'y' ) Z ')

somenamedtuple._source

A string with the pure Python source code used to create the named tuple class. The source makes the named tuple self-documenting. It can be printed, executed using exec() , or saved to a file and imported.

To create a pure Python code for a named tuple

in [36]: p._sourceout[36]:"From Builtins Import property as _property, tuple as _tuple\nfrom operator import Itemgetter as _itemgetter\nfrom collecti ONS import ordereddict\n\nclass Point (tuple): \ n ' point (x, Y, z) ' \ n \ __slots__ = () \ n \ _fields = (' x ', ' y ', ' z ') \ n def __new__ (_cls, x, Y, z): \ n ' Create new instance of point (X, Y, z) ' \ n return _tuple.__new__ (_CLS, (x, Y, z)) \ n \ @classmethod \ def _make (CLS, iterable, new=tuple.__new__, Len=len): \ n ' Make a new point object from a s equence or iterable ' \ n result = new (CLS, iterable) \ n If len (result)! = 3:\n Raise TypeError (' Expe  CTED 3 arguments, got%d '% len (result) \ n return result\n\n def _replace (_self, **kwds): \ n ' Return a new Point object replacing specified fields with new values ' \ n result = _self._make (Map (Kwds.pop, (' x ', ' y ', ' z '), _se LF) \ n if kwds:\n raise ValueError (' Got unexpected field names:%r '% list (kwds)) \ n return result \ n \ def __Repr__ (self): \ n ' return a nicely formatted representation string ' \ n return self.__class__.__name__ + ' (x=%r, y=%r, z=%r) '% self\n\n def _asdict (self): \ n ' Return a new ordereddict which maps field names to their values. ' \ n return ordereddict (Zip (self._fields, self)) \ nthe def __getnewargs__ (self): \ n ' return self as a plain tu  Ple. Used by copy and Pickle. ' \ n return tuple (self) \ nthe x = _property (_itemgetter (0), doc= ' Alias for field number 0 ') \ n \ nthe y = _property (_it Emgetter (1), doc= ' Alias for field number 1 ') \ nthe z = _property (_itemgetter (2), doc= ' Alias for field number 2 ') \ n \ nthe"

  

Python namedtuple (named tuples)

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.