#2의 배수
list1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
#3의 배수
list2 = [3, 6, 9, 12, 15, 18, 21]
교집합 intersection (A)
intersection = list1.intersection(list2)
print(intersection)
# error 발생 >> 'list' object has no attribute 'intersection'
# 꼭 set로 type 변경 필요
set1 = set(list1)
set2 = set(list2)
intersection = set1.intersection(set2)
print(intersection) # {6, 12, 18}
print(type(intersection)) # <class 'set'>
listIntersection = list(intersection)
print(listIntersection) # [18, 12, 6]
합집합 union (A + B + C)
# list끼리 더하기
addList = list1 + list2
addSet = set(addList)
print(addSet) # {2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21}
print(list(addSet)) # [2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21]
# 꼭 set로 type 변경 필요
set1 = set(list1)
set2 = set(list2)
union = set1.union(set2)
print(union) # {2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21}
차집합 difference (B)
# list 끼리 빼면...?
diff = list1 - list2
# error 발생 >> unsupported operand type(s) for -: 'list' and 'list'
diffSet = set1.difference(set2)
print(diffSet) #{2, 4, 8, 10, 14, 16, 20}
포함 관계 issubset(other)
set <= other
Test whether every element in the set is in other.
set < other
Test whether the set is a proper subset of other, that is, set <= other and set != other.
set3 = {3, 6, 9, 12, 15, 18, 21, 24}
set6 = {6, 12, 18, 24}
# set6 < set3 : set6이 set3에 포함됨
print(set3.issubset(set6)) # False
print(set6.issubset(set3)) # True
포함 관계 issuperset(other)
set >= other
Test whether every element in other is in the set.
set > other
Test whether the set is a proper superset of other, that is, set >= other and set != other.
set3 = {3, 6, 9, 12, 15, 18, 21, 24}
set6 = {6, 12, 18, 24}
# set6 < set3 : set6이 set3에 포함됨
print(set3.issuperset(set6)) # True
print(set6.issuperset(set3)) # False
서로소 isdisjoint(other)
- 교집합이 공집합이면, 즉 공통 원소가 없으면 True 반환
Q. list와 set의 차이, 다르게 사용하는 이유?
- 원소의 중복 가능 여부 >> 빈도 고려 시 list / 중복 원소 삭제 시 set.
- 중복 원소를 지우면 저장 공간에 두드러지는 이득이 있을까?
- index 유무
Further. set 원소 추가, 삭제