뮤트 개발일지

[파이썬 코딩 도장] Unit 26. 세트 사용하기 본문

코딩도장

[파이썬 코딩 도장] Unit 26. 세트 사용하기

박뮤트 2022. 1. 5. 22:55
>>> a = set('apple')    # 유일한 문자만 세트로 만듦
>>> a
{'e', 'l', 'a', 'p'}

>>> b = set(range(5))
>>> b
{0, 1, 2, 3, 4}

>>> c = set()
>>> c
set()

세트 만들기

세트set: 집합. 합집합, 교집합, 차집합 등의 연산이 가능하다.

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

중괄호로 표시하며, 순서가 없기 때문에 출력할 때마다 요소의 순서가 다르게 나온다. 또한 중복을 허용하지 않기 때문에 2개 이상인 요소는 한 개만 출력된다. 그리고 리스트, 튜플, 딕셔너리와 달리 []대괄호로 특정 요소만 출력할 수 없다는 특징을 가진다.

>>> fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'}
>>> print(fruits[0])
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
  
>>> print(fruits[0])
TypeError: 'set' object does not support indexing

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

세트에 특정한 값이 있는지 확인하기

>>> fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'}
>>> 'orange' in fruits
True
>>> 'peach' in fruits
False

반대로 not in 하면 반대의 결과가 출력된다.

set을 이용하여 세트 만들기

>>> a = set('apple')    # 유일한 문자만 세트로 만듦
>>> a
{'e', 'l', 'a', 'p'}

>>> b = set(range(5))
>>> b
{0, 1, 2, 3, 4}

>>> c = set()
>>> c
set()

* 이 때 c = {}를 하면 빈 딕셔너리가 만들어지므로 c = set()으로 빈 세트를 만들어주어야 한다.

세트 안에 세트 넣기

세트는 리스트, 딕셔너리와 달리 세트 안에 세트를 넣을 수 없다.

>>> a = {{1, 2}, {3, 4}}
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a = {{1, 2}, {3, 4}}
TypeError: unhashable type: 'set'

프로즌 세트

내용을 변경할 수 없는 세트다.

>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

집합 연산과 메소드에서 요소를 추가하거나 삭제하는 연산, 메소드는 사용할 수 없다.

>>> a = frozenset(range(10))
>>> a |= 10
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
  
    a |= 10
TypeError: unsupported operand type(s) for |=: 'frozenset' and 'int'

>>> a.update({10})
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    a.update({10})
AttributeError: 'frozenset' object has no attribute 'update'

frozenset를 사용하는 이유

세트 안에 세트를 넣고 싶을 때 사용한다. 세트 안에 세트는 허용하지 않지만 프로즌 세트는 들어갈 수 있다.

>>> frozenset({frozenset({1, 2}), frozenset({3, 4})})
frozenset({frozenset({1, 2}), frozenset({3, 4})})

집합 연산 사용하기

합집합 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}

교집합 intersection

>>> a & b
{3, 4}
>>> set.intersection(a, b)
{3, 4}

차집합 difference

>>> a - b
{1, 2}
>>> set.difference(a, b)
{1, 2}

대칭차집합 symmetric difference

>>> a ^ b
{1, 2, 5, 6}
>>> set.symmetric_difference(a, b)
{1, 2, 5, 6}

할당 연산자

|=, update()

>>> a = {1, 2, 3, 4}
>>> a |= {5}
>>> a
{1, 2, 3, 4, 5}
>>> a = {1, 2, 3, 4}
>>> a.update({5})
>>> a
{1, 2, 3, 4, 5}

&=, intersection_update()

>>> 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}

-=, difference_update()

>>> a = {1, 2, 3, 4}
>>> a -= {3}
>>> a
{1, 2, 4}
>>> a = {1, 2, 3, 4}
>>> a.difference_update({3})
>>> a
{1, 2, 4}

^=, symmetric_difference_update()

>>> 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}

부분집합 확인하기

<=, issubset()

>>> a = {1, 2, 3, 4}
>>> a <= {1, 2, 3, 4}
True
>>> a.issubset({1, 2, 3, 4, 5})
True

< 진부분집합

>>> a = {1, 2, 3, 4}
>>> a < {1, 2, 3, 4, 5}
True

상위집합 확인하기

>=, issuperset()

>>> 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 == {4, 2, 1, 3}
True

!= 은 반대로 출력

세트가 겹치지 않는지 확인하기, isdisjoint()

>>> a = {1, 2, 3, 4}
>>> a.isdisjoint({5, 6, 7, 8})       # 겹치는 요소가 없음
True
>>> a.isdisjoint({3, 4, 5, 6})    # a와 3, 4가 겹침
False

세트 조작하기

add(): 세트에 요소 추가하기

remove(): 세트에 특정 요소 삭제하기. 특정 요소가 없으면 에러 발생

discard(): 세트에 특정 요소 삭제하기. 특저 요소가 없으면 그냥 넘어감

pop(): 세트에 임의의 요소 삭제하기

clear(): 세트 비우기

len(): 세트의 요소 개수(길이) 구하기


세트의 할당과 복사

>>> a = {1, 2, 3, 4}
>>> b = a

>>> a is b
True

>>> b.add(5)
>>> a
{1, 2, 3, 4, 5}
>>> b
{1, 2, 3, 4, 5}

a, b를 완전히 다른 객체로 만들기 위해서는 copy()를 사용한다.

>>> a = {1, 2, 3, 4}
>>> b = a.copy()

>>> a is b
False
>>> a == b
True

>>> a = {1, 2, 3, 4}
>>> b = a.copy()
>>> 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 i in {1, 2, 3, 4}:
    print(i)
1
2
3
4

숫자는 순서대로 출력되지만 세트는 순서가 없기 때문에 다른 문자열 등이 들어가는 경우 출력될 때마다 결과 순서가 바뀐다.


세트 표현식 사용하기

>>> a = {i for i in 'apple'}
>>> a
{'l', 'p', 'e', 'a'}

중복된 것은 제외하고 순서 상관없이 출력된다.

>>> a = {i for i in 'pineapple' if i not in 'apl'}
>>> a
{'e', 'i', 'n'}