Named Tuple in Python

python中命名元组的使用

Often times, one dimensional data structure like array or list can not meet our needs.

For example, when we go through a string, we want to save some additional information along with the char at some particular position. How can we achieve this?

Namedtuple can help us, we can create a namedtuple and append it into an array.

from collections import namedtuple

Bracket = namedtuple("Bracket", ["char", "position"])

brt = Bracket('a', 1)

chars = []
chars.append(brt)

print(brt.position) # 1
print(brt.char) # a

相关文章: