강의노트 집합(set)

조회수 594 • 댓글 0 • 수정 1개월 전 크게 보기  
  • 집합
  • 자료 구조

집합

집합(set)은 중복되는 값을 허용하지 않고, 순서가 없는 자료형입니다.

딕셔너리와 같이 중괄호 {}로 만들지만, 딕셔너리와 달리 키-값 쌍이 아니라 값 하나만을 갖습니다.

집합은 중복된 값을 하나로 처리하여 저장하며, 인덱싱이 불가능합니다.

s = { 3,4,2,4,3,2,4,3,2,3,4,2}
print(s)

집합 연산

연산 설명 예시
& 교집합 A & B ; A.intersection(B)
| 합집합 A | B ; A.union(B)
- 차집합 A - B ; A.difference(B)
^ 대칭차집합 A ^ B ;
A = {1,2,3,4,5}
B = {3,4,5,6,7}

A & B    # {3, 4, 5}
A | B      # {1, 2, 3, 4, 5, 6, 7}
A - B     # {1, 2}
A ^ B    # {1, 2, 6, 7}
A = set('abracadabra')
B = set('alacazam')
A # unique letters in a
B
a in A
z in A
A - B # letters in a but not in b
A | B # letters in a or b or both
A & B # letters in both a and b
A ^ B # letters in a or b but not both

컴프리핸션과 집합

컴프리핸션 방법이 집합에서도 적용된다.

a = {x for x in 'abracadabra' if x not in 'abc'}

집합 조작 함수

함수 설명 예시
add 집합에 1개의 원소 추가 집합.add(원소)
update 집합에 여려개의 원소 추가 집합.update(리스트)
remove 하나의 원소만 삭제 집합.remove(삭제할 원소)
frozenset 업데이트가 되지 않는 집합 frozenset(집합)

집합 원소의 추가 및 삭제

A = { 1,2,3,4,5}
A.add(6)                  #{1, 2, 3, 4, 5, 6}
A.update([7,8,9])     #{1, 2, 3, 4, 5, 6, 7, 8, 9}
A.remove(3)            #{1, 2, 4, 5, 6, 7, 8, 9}

a = frozenset(['a', 'b', 'c']) 
b = {'a', 'b', 'c'}
a.remove('a')   # AttributeError: 'frozenset' object has no attribute 'remove'
b.remove('a')   # {'b', 'c'}

a.add('d')        # AttributeError: 'frozenset' object has no attribute 'add'
b.add('d')       # {'b', 'c', 'd'}
aa = list(a)
첫 글입니다.
마지막 글입니다.
댓글
댓글로 소통하세요.