본문 바로가기
Python

[Python] 집합 자료형

by 기리의 개발로그 2024. 1. 5.

집합 자료형

파이썬 집합에 관련된 것을 쉽게 처리하기 위한 자료형이다.
set() 키워드를 사용하여 만들 수 있다.
set() 괄호 안에 리스트/튜플이나 문자열을 입력하여 만들 수 있다.
반복가능한 자료형으로 생성 가능하다.(숫자형, 문자 여러 개로 생성 불가능)

s1 = set()
s2 = set([1,2,3])
print(s2)

s3 = set("hello")
print(s3)

s4 = set((4,2,5))
print(s4)

s4 = set(4,2,'hh','e')

s4 = set(4,2)
{1, 2, 3}

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

{2, 4, 5}

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got 4

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got 2

집합 자료형(set)은 중복을 허용하지 않으며 순서가 존재하지 않는다. 따라서, 인덱싱으로 값을 얻을 수 없다.
인덱싱으로 값을 얻기 위해서는 리스트나 튜플로 변환해야 한다.

s1 = set([1,2,3])
l1 = list(s1)

print(l1)
print(l1[0])

t1 = tuple(s1)
print(t1)
print(t1[0])
[1, 2, 3]
1

(1, 2, 3)
1

교집합, 합집합, 차집합


집합 자료형은 교집합, 합집합, 차집합을 구할 때 유용하게 사용할 수 있다.

교집합

& 기호 및 insertsection() 함수를 사용한다.

s1 = set([1,2,3,4,5,6])
s2 = set([4,5,6,7,8,9])

print(s1 & s2)
print(s1.intersection(s2))
{4, 5, 6}
{4, 5, 6}

합집합

| 기호 및 union() 함수를 사용한다.

s1 = set([1,2,3,4,5,6])
s2 = set([4,5,6,7,8,9])

print(s1 | s2)
print(s1.union(s2))
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 5, 6, 7, 8, 9}

차집합

- 기호 및 difference() 함수를 사용한다.

s1 = set([1,2,3,4,5,6])
s2 = set([4,5,6,7,8,9])

print(s1 - s2)
print(s2 - s1)
print(s1.difference(s2))
print(s2.difference(s1))
{1, 2, 3}
{8, 9, 7}
{1, 2, 3}
{8, 9, 7}
반응형

'Python' 카테고리의 다른 글

[python] 튜플(tuple)  (72) 2024.01.10
[Python] 집합 자료형 함수  (54) 2024.01.09
[Python] 딕셔너리 함수  (41) 2024.01.04
[Python] 딕셔너리(dictionary)  (45) 2024.01.03
[Python] 리스트 함수  (36) 2024.01.02

댓글