Sobes.tech
Junior

Ako sa v Pythone pristupuje k prvkom namedtuple?

sobes.tech AI

Odpoveď od AI

Prístup k prvkom namedtuple v Pythone sa vykonáva podľa názvu poľa alebo podľa indexu.

Podľa názvu poľa:

# Vytvorenie namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)

# Prístup podľa názvu
x_koordinata = p.x
y_koordinata = p.y

Podľa indexu:

# Vytvorenie namedtuple (používa sa ten istý 'Point' ako v predchádzajúcom príklade)
# from collections import namedtuple
# Point = namedtuple('Point', ['x', 'y'])
# p = Point(10, 20)

# Prístup podľa indexu
x_koordinata = p[0]
y_koordinata = p[1]

Použitím iterácie:

# Vytvorenie namedtuple (používa sa ten istý 'Point' ako v predchádzajúcom príklade)
# from collections import namedtuple
# Point = namedtuple('Point', ['x', 'y'])
# p = Point(10, 20)

# Iterácia cez prvky
for value in p:
    print(value)