Python 자료구조 2. tuple & set

이형래·2021년 8월 24일
2

Python

목록 보기
2/10
post-thumbnail

Python 자료구조

2. tuple & set

2.1 튜플 - tuple

  • 값의 변경이 불가능한 list.
  • tuple 선언 시 [ ] 가 아닌 ( ) 를 사용한다.
  • list 의 연산, indexing, slicing 등을 동일하게 사용한다.
>>> tuple_a = (1, 2, 3, 4, 5)		# tuple 선언

>>> type(tuple_a)			# type check
<class 'tuple'>

>>> tuple_a[0] = 42			# 값 변경 시도
Traceback (most recent call last):	# Error
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> tuple_b = (1)			# int로 인식함.
>>> type(tuple_b)
<class 'int'>

>>> tuple_c = (1,)			# 요소가 1개인 tupel은 반드시 ','를 붙여 사용한다.
>>> type(tuple_c)
<class 'tuple'>

tuple의 사용.

  • 프로그램 작동중에 변경되어서는 안되는 데이터를 저장한다. ex) userID
  • 위의 데이터들을 tuple로 저장하면 함수의 return값 등 실수에 의한 에러를 방지할 수 있다.

2.2 집합 - set

  • 값을 순서없이 저장한다. (Unordered)
    -> 인덱싱으로 값을 얻을 수 없다.
  • 중복을 허용하지 않는다.
  • set 객체 선언을 이용하여 생성한다.
>>> set_a = set([1, 2, 3, 4, 5])	# set_a 생성
>>> set_a
{1, 2, 3, 4, 5}

>>> set_a = set([1, 2, 3, 4, 5, 1, 2, 3, 4, 5])
>>> set_a				# 중복된 원소를 허용하지 않는다.
{1, 2, 3, 4, 5}

>>> type(set_a)				# type check
<class 'set'>

>>> set_a[0]				# indexing 으로 값을 얻을 수 없다.
Traceback (most recent call last):	# Error
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable

>>> set_b = {6, 7, 8, 9, 10}		# 이렇게도 set 생성 가능.
>>> type(set_b)
<class 'set'>

관련 함수들.

  • 값 1개 추가: add
>>> set_a.add(6)
>>> set_a
{1, 2, 3, 4, 5, 6}
  • 값 여러개 추가: update
>>> set_a.update([1, 3, 5, 7, 9])
>>> set_a
{1, 2, 3, 4, 5, 6, 7, 9}
  • 특정 값 제거: remove, discard
>>> set_a.remove(1)
>>> set_a
{2, 3, 4, 5, 6, 7, 9}

>>> set_a.discard(2)
>>> set_a
{3, 4, 5, 6, 7, 9}
  • 모든 원소 삭제: clear
>>> set_a.clear()
>>> set_a
set()

set의 사용.
주로 교집합, 합집합, 차집합등을 구할때 사용한다.
기본적인 집합 메소드를 지원함.
교집합 - set_a.intersection(set_b)
합집합 - set_a.union(set_b)
차집합 - set_a.difference(set_b)

profile
머신러닝을 공부하고 있습니다. 특히 비전 분야에 관심이 많습니다.

0개의 댓글