세트 = 집합을 표현하는 자료형
- 세트 = {값1,값2,값,3}
세트의 특징
- 순서가 없다. (숫자의 경우 순서대로 출력된다.)
- 요소의 중복이 안된다.
- 특정 요소만 출력할 수 없다(시퀀스 객체들은 인덱스 등의 접근으로 단일 요소만 출력이 가능)
fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry','orange'}
fruits
{'pineapple', 'orange', 'grape', 'strawberry', 'cherry'}
fruits
{'grape','pineapple', 'strawberry', 'cherry','orange'}
fruits[0]
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
fruits[0]
TypeError: 'set' object is not subscriptable
세트는 순서가 없다. 그래서 매번 다르게 나온다.
세트에 특정 값이 있는지 확인하기
- 값 in 세트
- 값 not in 세트
fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'}
'orange' in fruits
True
'peach' in fruits
False
'apple' not in fruits
True
set을 사용하여 세트 만들기
- set(반복가능한객체)
a = set('apple')
a
{'e','l','a','p'}
#순서가 없고 중복된 'p'는 한번만 출력
b = set(range(5))
b
{0,1,2,3,4}
#빈 세트 만들기
c = set()
c
set()
#빈세트 잘못만든 예
d = {}
type(c)
<class 'set'>
type(d)
<class 'dict'>
#d = {} 사용시 딕셔너리가 생성된다.
프로즌 세트
변경이 불가능한 세트
- 프로즌세트 = frozenset(range(10))
수정이 불가능한 세트를 왜 만들까? 바로 세트안에 세트를 넣기 위함이다.
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'
#세트안에 세트를 넣을시 오류가 난다.
frozenset({frozenset({1, 2}), frozenset({3, 4})})
frozenset({frozenset({1, 2}), frozenset({3, 4})})
#프로즌 세트를 활용하면 가능하다.
집합 연산자 사용하기
합집합(union)
- 세트1 | 세트2
- set.union(세트1,세트2)
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)
- 세트1 & 세트2
- set.intersection(세트1,세트2)
a & b
{3, 4}
set.intersection(a, b)
{3, 4}
차집합(difference)
- 세트1 - 세트2
- set.difference(세트1,세트2)
a - b
{1, 2}
set.difference(a, b)
{1, 2}
대칭집합(symmetric difference)
대칭집합이란 합집합에서 교집합을 뺀것.즉, 서로 겹친 부분을 제외한 모든것이다.
- 세트1 ^ 세트2
- set.symmetric_difference(세트1,세트2)
a ^ b
{1, 2, 5, 6}
set.symmetric_difference(a, b)
{1, 2, 5, 6}
집합 연산 후 할당 연산자 사용하기
- 집합연산자는 집합연산후 "반환"한다 하지만 할당 연산자는 "할당"을 한다.
합집합
- 세트1 |= 세트2
- 세트1.update(세트2)
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}
교집합 할당 연산자
- 세트1 &= 세트2
- 세트1.intersection_update(세트2)
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}
차집합 할당 연산자
- 세트1 -= 세트2
- 세트1.difference_update(세트2)
a = {1, 2, 3, 4}
a -= {3}
a
{1, 2, 4}
a = {1, 2, 3, 4}
a.difference_update({3})
a
{1, 2, 4}
대칭 차집합 할당 연산자
- 세트1 ^= 세트2
- 세트1.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}
부분집합과 상위집합 확인하기
부분집합(subset)
- 현재세트<= 다른세트
- 현재세트.issubset(다른세트)
a = {1, 2, 3, 4}
a <= {1, 2, 3, 4}
True
a.issubset({1, 2, 3, 4, 5})
True
진부분집합(proper subset)
- 현재세트 < 다른세트
a = {1, 2, 3, 4}
a < {1, 2, 3, 4, 5}
True
상위집합 (superset)
- 현재세트 >= 다른세트
- 현재세트.issuperset(다른세트)
a = {1, 2, 3, 4}
a >= {1, 2, 3, 4}
True
a.issuperset({1, 2, 3, 4})
True
진상위집합 (proper superset)
- 현재세트 > 다른세트
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, 4}
a != {1, 2, 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 = 세트에 요소를 추가
a = {1, 2, 3, 4}
a.add(5)
a
{1, 2, 3, 4, 5}
remove = 세트의 특정요소 삭제
a = {1,2,3,4,5}
a.remove(3)
a
{1, 2, 4, 5}
- 요소가 없을시 오류가 발생
discord = 세트의 특정 요소 삭제
a={1,2,3,4}
a.discard(2)
a
{1,3,4}
a.discard(5)
a
{1,3,4}
pop = 세트에서 임의 요소 삭제
a = {1, 2, 3, 4}
a.pop()
3
a
{1, 2, 4}
- 삭제한값 반환
- 요소가 없을시 오류가 발생
clear = 세트의 모든 요소 삭제
a = {1,2,3,4}
a.clear
a
set()
len 세트의 요소 개수 구하기
a = {1,2,3,4}
len(a)
4
세트의 할당과 복사
앞에 다뤘던 리스트, 딕셔너리와 같다.
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 = {1,2,3,4}
b = a.copy()
a is b
False
a == b
True #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 변수 in 반복가능한객체}
- set(식 for 변수 in 반복가능한객체)
a = {i for i in 'apple'}
a
{'l','p','e','a'} #중복된것을 제외하고 무작위순으로 출력
#세트 표현식을 쓰지 않는다면?
for i in {'apple'}:
print(i)
apple
세트표현식에 if 조건문 사용
- {식 for 변수 in 세트 if 조건식}
- set(식 for 변수 in 세트 if 조건식)
a = {i for i in 'pineapple' if i not in 'apl'}
a
{'e','i','n'}
'Python > 기초문법' 카테고리의 다른 글
(22)회문 & N-gram (0) | 2022.04.06 |
---|---|
(21)파이썬으로 파일에 문자열 쓰고,읽기 (0) | 2022.04.05 |
(19)딕셔너리 활용하기 (0) | 2022.04.03 |
(18)서식 지정자 & 포맷 메서드 (0) | 2022.04.02 |
(17) 문자열 메소드 (0) | 2022.04.01 |