目录
- 简述
- API
- 例子
简述
namedtuple
是对tuple的扩展,支持用名称访问tuple中的元素.
Python文档
API
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
classmethod somenamedtuple._make(iterable)
Class method that makes a new instance from an existing sequence or iterable.somenamedtuple._asdict()
Return a new dict which maps field names to their corresponding values:somenamedtuple._replace(**kwargs)
Return a new instance of the named tuple replacing specified fields with new values:somenamedtuple._fields
Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.somenamedtuple._field_defaults
Dictionary mapping field names to default values.
例子
from collections import namedtuple
# define the named tuple
Point = namedtuple('Point', 'x,y')
Point2 = namedtuple('Point', 'x y')
# create a namedtuple instance
p1 = Point(1, 2)
p2 = Point2(x=3, y=4)
# reference the fields
p1.x # using the dot.
p1[1] # using subscript
# the instances are type Point
type(p1) #
type(p2) #
# the defined namedtuple are type of 'type'
type(Point) #
type(Point2) #
# as tuple, namedtuple is immutable too, can not change the fields value
p1.x = 4 # WRONG
# instead we can replace the value using api.
p2 = p2._replace(x=4) # OK
# ---- create instance with _make
Metric = namedtuple('Metric', 'a,b,c,d,e,f,g')
value = [i for i in range(len(Metric._fields))]
# create instance using either _make or init parameters
m1 = Metric(*value) # Metric(a=0, b=1, c=2, d=3, e=4, f=5, g=6)
m2 = Metric._make(value) # Metric(a=0, b=1, c=2, d=3, e=4, f=5, g=6)
# convert to a dictionary
m1._asdict() # {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6}
# ---- extend the namedtuple
# the namedtuple can be subclassed
class Point(namedtuple('Point', 'x, y')):
def distance_to_origin(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def __str__(self):
return f'x: {self.x}, y: {self.y}, distance to origin: {self.distance_to_origin()}'
p = Point(x=3, y=4)
str(p) # 'x: 3, y: 4, distance to origin: 5.0'
# add more fields
Point3D = namedtuple('Point3D', Point._fields + ('z',))
p3d = Point3D(x=1, y=2, z=3)
p3d # Point3D(x=1, y=2, z=3)