-
Python Class - 4Programming/python 2021. 6. 29. 21:04728x90
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
'Programming > python' 카테고리의 다른 글
Python Class - 5 (0) 2021.06.29 Python Class - 3 (0) 2021.06.24 Python Class - 2 (0) 2021.06.24 Python Class - 1 (0) 2021.06.24 다익스트라(Dijkstra) 알고리즘 (0) 2021.03.10