Python

set

haventmetyou 2023. 10. 11. 14:04

집합을 표현하는 세트(set) 자료형으로 합집합, 교집합, 차집합 등의 연산 가능

>>> fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'}
>>> fruits
{'cherry', 'pineapple', 'strawberry', 'grape', 'orange'}

>>> fruits = {'orange', 'orange', 'cherry'}
>>> fruits
{'cherry', 'orange'}

요소의 순서가 정해져 있지 않아 출력할 때마다 요소의 순서가 다르게 나옴

요소 중복될 수 없음

>>> fruits['cherry']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable

리스트, 튜플, 딕셔너리와는 달리 [](대괄호)로 특정 요소만 출력할 수 없음

>>> # 세트에 특정 값이 있는지 확인
>>> fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'}
>>>
>>> 'orange' in fruits
True
>>> 'peach' in fruits
False
>>> 'peach' not in fruits
True
>>> 'orange' not in fruits
False

 

>>> # 세트 자료구조 만들기
>>> a = {'apple', 'orange', 'cherry'}
>>> b = set('apple')
>>> c = set()    # 빈 세트
>>>
>>> # 딕셔너리 자료구조
>>> d = {'name':'cat', 'age':3}
>>> e = dict( [['name', 'age'], ['cat', 3]] )
>>> f = {}    # 빈 딕셔너리
>>>
>>> # 타입 알아보기
>>> c = {}
>>> type(c)
<class 'dict'>
>>>
>>> c = set()
>>> type(c)
<class 'set'>

 

집합 연산 사용
>>> # 세트의 합집합(union)
>>> a = {1, 2, 3, 4}
>>> b = {3, 4, 5, 6}
>>> a|b
{1, 2, 3, 4, 5, 6}
>>> set.union(a, b)
{1, 2, 3, 4, 5, 6}
>>> a or b
{1, 2, 3, 4}
>>> set.union( {1, 2, 3, 4}, {3, 4, 5, 6} )
{1, 2, 3, 4, 5, 6}
>>> a & b
{3, 4}
>>> set.intersection(a, b)
{3, 4}
>>> set.intersection(b, a)
{3, 4}
>>>
>>> # 차집합
>>> a = {1, 2, 3, 4}
>>> b = {3, 4, 5, 6}
>>> a - b
{1, 2}
>>> b - a
{5, 6}
>>> set.difference(a, b)
{1, 2}
>>> set.difference(b, a)
{5, 6}
>>>
>>> # 교집합
>>> a = {1, 2, 3, 4}
>>> b = {3, 4, 5, 6}
>>> set.intersection(a, b)
{3, 4}
>>> a & b
{3, 4}
>>>
>>> # 대칭차집합
>>> a = {1, 2, 3, 4}
>>> b = {3, 4, 5, 6}
>>> a ^ b
{1, 2, 5, 6}
>>> set.symmetric_difference(a, b)
{1, 2, 5, 6}
>>>
>>> # 집합 연산을 한 후 할당 연산
>>> # 현재 세트 + 다른 세트
>>> a = {1, 2, 3, 4}
>>> b = {5}
>>> c = a|b
>>> c
{1, 2, 3, 4, 5}
>>>
>>> # 간단히 다시 쓰기
>>> a = {1, 2, 3, 4, 5}
>>> a |= {5}    # 집합 a에 {5}를 |(합집합) 연산 후 할당
>>>
>>> a.update( {5} )
>>> a
{1, 2, 3, 4, 5}
>>>
>>> # 겹치는 요소 저장
>>> a = {1, 2, 3, 4}
>>> a &= {0, 1, 2, 3, 4}
>>> a
{1, 2, 3, 4}
>>> a = {1, 2, 3, 4}
>>> a.intersection_update( {0, 1, 2, 3, 4} )
>>> a
{1, 2, 3, 4}
>>>
>>> # 현재 세트 - 다른 세트 
>>> a = {1, 2, 3, 4}
>>> a -= {3}
>>> a
{1, 2, 4}
>>> a = {1, 2, 3, 4}
>>> a.difference_update({3})
>>> a
{1, 2, 4}
>>>
>>> # 겹치지 않는 요소 저장
>>> a = {1, 2, 3, 4}
>>> a ^= {3, 4, 5, 6}
>>> a
{1, 2, 5, 6}
>>> a = {1, 2, 3, 4}
>>> a.symmetric_difference_update({3, 4, 5, 6})
>>> a
{1, 2, 5, 6}
>>>
>>> # 부분집합
>>> a = {1, 2, 3, 4}
>>> a <= {1, 2, 3, 4}
True
>>> a.issubset( {1, 2, 3, 4} )
True
>>>
>>> # 진부분집합
>>> a = {1, 2, 3, 4}
>>> a < {1, 2, 3, 4, 5}
True
>>>
>>> # 상위집합
>>> a = {1, 2, 3, 4}
>>> a >= {1, 2, 3, 4}
True
>>> a.issuperset( {1, 2, 3, 4} )
True
>>>
>>> # 진상위집합
>>> a = {1, 2, 3, 4}
>>> a > {1, 2, 3}
True
>>>
>>> # 세트가 같은지 다른지 확인
>>> a = {1, 2, 3, 4}
>>> a == {1, 2, 3, 4}
True
>>> a == {4, 2, 1, 3}
True    # 세트는 요소의 순서가 정해져 있지 않으므로 각 요소만 같으면 참
>>> a != {1, 2, 3}
True
>>>
>>> # 세트가 겹치지 않는지 확인
>>> a = {1, 2, 3, 4}
>>> a.isdisjoint( {5, 6, 7, 8} )    # 겹치는 요소 없음
True
>>>
>>> a & {5, 6, 7, 8}
set()
>>> a
{1, 2, 3, 4}
>>>
>>> a.isdisjoint( {3, 4, 5, 6} )    # a와 3, 4가 겹침
False

 

세트 조작
>>> # 세트 요소 추가
>>> a = {1, 2, 3, 4}
>>> a.add(5)
>>> a
{1, 2, 3, 4, 5}
>>>
>>> # 세트 특정 요소 삭제
>>> a.remove(3)
>>> a
{1, 2, 4, 5}
>>> a.discard(2)
>>> a
{1, 4, 5}
>>> a.discard(3)
>>> a
{1, 4, 5}
>>>
>>> # 세트에서 임의의 요소 삭제
>>> a = {1, 2, 3, 4}
>>> a.pop()
1
>>> a
{2, 3, 4}
>>>
>>> # 세트의 모든 요소 삭제
>>> a.clear()
>>> a
set()
>>>
>>> # 세트의 요소 개수 구하기
>>> a = {1, 2, 3, 4}
>>> len(a)
4
>>>
>>> a = [1, 2, 2, 3, 4]
>>> a.pop()    # 마지막 요소 제거
4
>>> a.pop()    # 마지막 요소 제거
3
>>>
>>> a = [1, 2, 2, 3, 4]
>>> a.count(2)    # 값이 2인 요소의 개수
2
>>> len(a)        # 리스트 a의 길이(크기)
5

 

세트의 할당과 복사
>>> a = {1, 2, 3, 4}
>>> b = a
>>>
>>> a is b    # 변수 이름만 다를 뿐 같은 객체, 세트 1개
True
>>>
>>> b.add(5)
>>> a
{1, 2, 3, 4, 5}
>>> b
{1, 2, 3, 4, 5}    # 같은 객체이므로 a와 b 모두 반영됨
>>>
>>> a = {1, 2, 3, 4}
>>> b = a.copy()
>>>
>>> a is b
False
>>> a == b    # copy로 서로 다른 객체가 됐지만 복사한 요소는 같기 때문에
True	      # True 출력
>>>
>>> b.add(5)
>>> a
{1, 2, 3, 4}
>>> b
{1, 2, 3, 4, 5}

 

반복문으로 세트 요소 모두 출력
>>> a = {1, 2, 3, 4}
>>> for i in a:
...     print(i)
...
1
2
3
4
>>> # 세트의 요소는 순서가 없으므로 출력할 때마다 달라짐
>>> # 숫자로만 이루어진 세트는 순서대로 출력됨
>>>
>>>
>>> # for 반복문을 이용해 세트 a를 리스트 형태로 변환
>>> l = []
>>> a = {1, 2, 3, 4}
>>>
>>> for i in a:
...     print(i)
...     l.append(i)
...
1
2
3
4
>>> l
[1, 2, 3, 4]

 

세트 표현식 사용
>>> a = {i for i in 'apple'}
>>> a
{'p', 'e', 'l', 'a'}
>>>
>>> a = set()    # 빈 집합 만들기
>>> for i in 'apple':
...     a.update(i)
...
>>> a
{'p', 'e', 'l', 'a'}
>>>
>>> # 세트 표현식에 if 조건문 사용
>>> a = { i for i in 'pineapple' if i not in 'apl' }
>>> a
{'i', 'e', 'n'}
>>> for i in 'pineapple':
...     if i not in 'apl':
...         print(i)
...
i
n
e
e
>>>