[Python] 집합과 튜플

DongHyeon Jung·2022년 9월 17일
0

Python

목록 보기
4/8
post-thumbnail

집합

  • 객체를 중복 없이 저장할 수 있는 유ㅜ용한 자료구조
  • 리스트나 딕셔너리처럼 크기를 늘릴 수 있다
  • 하지만 딕셔너리처럼 순서가 없다
  • 빠른 검색에 최적화
>>> vowels = {'a', 'e', 'e'}
>>> vowels
{'a', 'e'}

# set method
>>> word = set('asdfqwer')
>>> word
{'e', 'd', 'a', 'w', 'r', 'f', 's', 'q'}

union

word = 'hello'
vowels = set('asdf')
u = vowels.union(set(word))

{'h', 'e', 'l', 'd', 'a', 'o', 'f', 's'}

difference

d = vowels.difference(set(word))
d
{'s', 'a', 'f', 'd'}

vowels에는 포함되어 있지만 word에는 포함되어 있지 않은 객체

intersection

vowels = {'a', 'e', 'e', 'd', 'h', 'l'}  
word = 'hello'  
  
i = vowels.intersection(set(word))  

{'l', 'h', 'e'}

튜플

  • 변경할 수 없는 리스트
  • 상수 리스트이다
  • 인덱스를 사용한다
vowels = ( 'a', 'e', 'e', 'd', 'h', 'l')
vowels = ('a', 'e', 'e', 'd', 'h', 'l')  
  
vowels[2] = "F"

Traceback (most recent call last):
File "/Users/jayden/PycharmProjects/pythonProject2/for.py", line 3, in
vowels[2] = "F"
TypeError: 'tuple' object does not support item assignment

에러가 발생하는 것을 알 수 있다

그렇다면 변경할 수 없는 리스트를 어디에 쓸까?

자료구조의 데이터가 절대 바뀌지 않을 때 사용된다

0개의 댓글