Python

[Python] namedtuple in collections

llHoYall 2021. 5. 2. 16:25

namedtuple can give a name to each element of tuple.

from collections import namedtuple

Point = namedtuple('Name', ['x', 'y'])
pt = Point(1, 2)
print(pt)
# Name(x=1, y=2)

print(pt.x, pt.y)
# 1 2

Attributes

_fields

Tuple of strings listing the field names.

print(pt._fields)
# ('x', 'y')

_field_defaults

Dictionary mapping field names to default values.

Point = namedtuple('Name', ['x', 'y'], defaults=[0])
pt = Point(1)
print(pt)
# Name(x=1, y=0)

print(pt._field_defaults)
# {'y': 0}

Point2 = namedtuple('Name2', Point._fields + ('z', ), defaults=[0, 1])
pt2 = Point2(3)
print(pt2)
# Name2(x=3, y=0, z=1)

print(pt2._field_defaults)
# {'y': 0, 'z': 1}

Methods

_make(iterable): classmethod

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

test_list = [3, 7]
pt = Point._make(test_list)
print(pt)
# Name(x=3, y=7)

_asdict()

Return a new dict which maps field names their corresponding values.

pt = Point(2, 5)
print(pt._asdict())
# {'x': 2, 'y': 5}

_replace(**kwargs)

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

pt = Point(1, 3)
print(pt._replace(x=2))
# Name(x=2, y=3)

print(pt)
# Name(x=1, y=3)

Conclusion

tuple doesn't support naming to its member element.

If you need to give them a name, you can use namedtuple.

반응형