Python

[파이썬] set 함수

bornsoon 2024. 12. 1. 12:46

add

한 개의 자료형을 추가할 때

my_set = set(['a', 'b', 'c'])
my_set.add('d')

print(my_set)  # {'a', 'b', 'c', 'd'}

 

update

여러 개를 한꺼번에 추가할 때

my_set = set(['a', 'b', 'c'])
my_set.update(['d', 'e', 'f'])

print(my_set)  # {'a', 'b', 'c', 'd', 'e', 'f'}

 

remove

 특정 값을 제거할 때

my_set = set(['a', 'b', 'c'])
my_set.remove('b')

print(my_set)  # {'a', 'c'}

 

 

 

------------------------------------------------------------------------------------------------------------------------------

<집합 연산>

 

합집합 ( ' | ' , union )

my_set1 = {'a', 'b', 'c'}
my_set2 = {'d', 'e', 'f'}

my_set1 | my_set2
# {'a', 'b', 'c', 'd', 'e', 'f'}

my_set1.union(my_set2)
# {'a', 'b', 'c', 'd', 'e', 'f'}

 

교집합 ( ' & ' , intersection )

my_set1 = {'a', 'b', 'c', 'd'}
my_set2 = {'b', 'c', 'd', 'e', 'f'}

my_set1 & my_set2
# {'b', 'c', 'd'}

my_set1.intersection(my_set2)
# {'b', 'c', 'd'}

 

차집합 ( ' - ' , difference )

my_set1 = {'a', 'b', 'c', 'd'}
my_set2 = {'b', 'c', 'd', 'e', 'f'}

my_set1 - my_set2
# {'a'}

my_set1.difference(my_set2)
# {'a'}

my_set2 - my_set1
# {'e', 'f'}

my_set2.difference(my_set1)
# {'e', 'f'}


대칭차집합 ( ' ^ ' , symmetric_difference ) ( (A-B) | (B-A) )

my_set1 = {'a', 'b', 'c', 'd'}
my_set2 = {'b', 'c', 'd', 'e', 'f'}

my_set1 ^ my_set2
# {'a', 'e', 'f}

my_set1.symmetric_difference(my_set2)
# {'a', 'e', 'f}


부분집합 ( ' >= ' , ' <= ' )

my_set1 = {1, 2, 3}
my_set2 = {2, 3}

my_set1 >= my_set2
# True

 

728x90