What is Namedtuple in Python? 

Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.

collections.namedtuple(typenamefield_names[verbose=False][rename=False])

Just a simple example. 

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'], verbose=True)

p = Point(11, y=22)     # instantiate with positional or keyword arguments
p[0] + p[1]             # indexable like the plain tuple (11, 22)

x, y = p                # unpack like a regular tuple
p.x + p.y               # fields also accessible by name

0 comments

Popular Posts

无觅相关文章插件,迅速提升网站流量