What are “named tuples” in Python?

前端 未结 11 2282
名媛妹妹
名媛妹妹 2020-11-22 06:58

Reading the changes in Python 3.1, I found something... unexpected:

The sys.version_info tuple is now a named tuple:

11条回答
  •  清歌不尽
    2020-11-22 07:15

    Try this:

    collections.namedtuple()
    

    Basically, namedtuples are easy to create, lightweight object types. They turn tuples into convenient containers for simple tasks. With namedtuples, you don’t have to use integer indices for accessing members of a tuple.

    Examples:

    Code 1:

    >>> from collections import namedtuple
    
    >>> Point = namedtuple('Point','x,y')
    
    >>> pt1 = Point(1,2)
    
    >>> pt2 = Point(3,4)
    
    >>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )
    
    >>> print dot_product
    11
    

    Code 2:

    >>> from collections import namedtuple
    
    >>> Car = namedtuple('Car','Price Mileage Colour Class')
    
    >>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y')
    
    >>> print xyz
    
    Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y')
    >>> print xyz.Class
    Y
    

提交回复
热议问题