Programming/python
Python Class - 4
홍열
2021. 6. 29. 21:04
728x90
1) NamedTuple
일반적인 tuple을 사용할때는 [0], [1]으로 접근을 해야한다.
# 일반적인 튜플 사용
pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)
from math import sqrt
line_leng1 = sqrt((pt2[0] - pt1[0]) ** 2 + (pt2[1] - pt1[1]) ** 2)
하지만 이름으로 접근해야할때는 어떻게 해야될까?
좌표계 예제인데, [0],[1]이 아닌 x,y로 접근하고 싶다.
이럴때 collections의 namedtuple을 사용하면 된다.
# 네임드 튜플 선언
Point = namedtuple('Point', 'x y')
# 두 점 선언
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
# 계산
line_leng2 = sqrt((pt2.x - pt1.x) ** 2 + (pt2.y - pt1.y) ** 2)
https://docs.python.org/ko/3.7/library/collections.html
collections — Container datatypes — Python 3.7.11 문서
collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f
docs.python.org