shiqi

shiqi

Study GIS, apply to world
twitter
github
bento
jike

namedtuple in Python

namedtuple is a data structure in the Python standard library, located in the collections module. It is a factory function used to create tuples with field names, allowing tuple fields to be accessed like object properties without needing to use indexes.

Using namedtuple makes it easy to define a tuple type with field names without manually writing a class. This is very useful when a lightweight data container is needed, but you still want to access the data like object properties.

Here is a simple example demonstrating how to use namedtuple:

from collections import namedtuple

# Define a namedtuple named Point with two fields: x and y
Point = namedtuple('Point', ['x', 'y'])

# Create a Point object
p1 = Point(1, 2)

# Access fields
print(p1.x)  # Output: 1
print(p1.y)  # Output: 2

In the example above, we defined a namedtuple named Point with two fields x and y. Then, we created a Point object p1 and accessed its values using field names.

View Example#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.