티스토리 뷰

Basic

파이썬 Tuple

nickas 2020. 4. 19. 22:00

Tuplelistdictionary와 다른게 한번 만들어 지면 변경될 수 없음(immutable).
데이터 모음이 변경되지 않는 것을 보장해야 할 때 사용.
()를 사용하여 만듬.

Tuple 만들기

>>> t = ()       # 빈 tuple 
>>> t = tuple()  # tuple() 빌트인 함수 사용

아이템 추가

한번 만들어진 tuple은 아이템을 추가하거나 변경 할 수 없기 때문에 사실상 아이템을 추가 할 수 있는 방법이 없고 tuple을 만들면서 아이템을 추가하여야 함.

>>> t = (0,)
>>> t = 0, 'spam', 1.2
>>> t = tuple('spam')
('s', 'p', 'a', 'm')

>>> t = tuple(0)  # iterable한 아이템만 사용가능
TypeError: 'int' object is not iterable

(주의) t = (0) 이렇게 ,(콤마) 없이 사용하면 그냥 integer 타입이 됨. 반드시 콤마를 사용해야 함.

아이템 가져오기

list와 같이 index를 사용.

>>> t = (0, 1, 2, 3)
>>> t[0]
0

netsted 아이템 가져오기

사용법은 list와 같음

>>> t = (1, [2, 3], 4)
>>> t[1][0]
2

아이템 변경하기

한번 만들어지 tuple은 아이템을 변경 할 수 없음.

>>> t = (0, 1, 2, 3)
>>> t[0] = 4
TypeError: 'tuple' object does not support item assignment

그러나 nested 아이템이 list 같이 mutable 아이템이면 변경가능.

>>> t = (0, [1, 2], 3)
>>> t[1][0] = 'a'
>>> t
(0, ['a', 2], 3)

Nested된 mutable 아이템을 사용할 때 주의사항

>>> l = [0, 1]
>>> t = (0, l, 2)
>>> t
(0, [0, 1], 2)

>>> l[0] = 3  # list 아이템을 변경 시 tuple에서 사용한 list도 같이 변경 됨
>>> t
(0, [3, 1], 2)

연산

>>> (1, 2) + (3, 4)
(1, 2, 3, 4)
>>> (1, 2) * 4
(1, 2, 1, 2, 1, 2, 1, 2)

Slicing

사용법은 list와 같음

>>> t = 0, 1, 2, 3
>>> t[1:3]
(1, 2)

정렬하기

# list로 변환 후 .sort() 메서드 사용
>>> t = (3, 2, 1, 0)
>>> l = list(t)
>>> l.sort()
>>> l
[0, 1, 2, 3]
>>> t = tuple(l)
>>> t
(0, 1, 2, 3)

# sorted() 빌트인 함수 사용
>>> t = (3, 2, 1, 0)
>>> sorted(t)
[0, 1, 2, 3)

Tuple 메서드

.index()

아이템의 index 위치를 반환

>>> t = ('a', 'b', 'c')
>>> t.index('a)
0

# 중복된 아이템이 있을 경우 사용
>>> t = ('a', 'b', 'a', 'c')
>>> t.index('a', 2)  # 두 번째 a의 위치를 반환
2

.count()

아이템 갯수를 반환

>>> t = (1, 2, 3, 2, 3, 2)
>>> t.count(2)
3

namedtuple

Dictionary 비스므리하게 사용하기 위해 사용.
tuple/class/dictionary의 하이브리드 형태.

>>> from collections import namedtuple
# 레코드 이름과 필드 설정
>>> rec = namedtuple('rec', ['name', 'age', 'jobs'])
>>> john = rec('John', age=50, jobs=['dev', 'mgr'])
>>> john
rec(name='John', age=50, jobs=['dev', 'mgr'])
>>> john[0]
'John'
>>> john.name
'John'

>>> john._asdict()  # Dictionary로 만들어 줌.
{'name': 'John', 'age': 50, 'jobs': ['dev', 'mgr']}
>>> john._asdict()['name']
'John'

 

'Basic' 카테고리의 다른 글

파이썬 조건문 그리고 반복문  (0) 2020.04.26
Set  (0) 2020.04.25
파이썬 Dictionary  (0) 2020.04.19
파이썬 List  (0) 2020.04.12
파이썬 String  (0) 2020.04.11
최근에 올라온 글
글 보관함