Python/Data Struc & algo
[Python] collections namedtuple (이름을 가진 튜플)
Pydole
2018. 5. 19. 16:06
DOCS : https://docs.python.org/3/library/collections.html?highlight=namedtuple#collections.namedtuple
- 인덱스로 요소를 접근하는 튜플보다 Naming으로 직관적으로 접근이 가능. (마치 사전처럼)
- 변경 불가능한 자료형(immutable)으로 요소를 변경하지 않을 경우 사전보다 성능에 이점이 있다.
namedtuple (네임드 튜플)
import collections
Score = collections.namedtuple('Score', 'english math music ')
Student1 = Score(english=90, math=80, music=85)
print(Student1.english, Student1[0]) # name와 index 둘다 접근이 가능
print(Student1.math, Student1[1])
print(Student1.music, Student1[2])
90 90
80 80
85 85
사전(Dict)
Score = {'english':90, 'math':80, 'music':85}
print(Score['english'])
print(Score['math'])
print(Score['music'])
90
80
85