문자열 집합에 대해 알아보기
이 단계에서는 Python 에서 문자열 집합에 대해 배우게 됩니다. 집합 (set) 은 고유한 요소들의 정렬되지 않은 컬렉션입니다. 즉, 집합은 중복된 값을 포함할 수 없습니다. 집합은 합집합 (union), 교집합 (intersection), 차집합 (difference) 과 같은 수학적 집합 연산을 수행하는 데 유용합니다. 이 랩에서는 문자열을 포함하는 집합에 중점을 둡니다.
먼저, 간단한 문자열 집합을 만들어 보겠습니다. LabEx 환경에서 VS Code 편집기를 엽니다. ~/project 디렉토리에 string_sets.py라는 새 파일을 만듭니다.
## ~/project/string_sets.py
string_set = {"apple", "banana", "cherry"}
print(string_set)
파일을 저장합니다. 이제 터미널에서 python 명령을 사용하여 스크립트를 실행합니다.
python ~/project/string_sets.py
다음과 같은 출력을 볼 수 있습니다 (집합은 정렬되지 않으므로 요소의 순서는 다를 수 있습니다).
{'cherry', 'banana', 'apple'}
이제 집합에 중복된 요소를 추가하고 어떤 일이 발생하는지 살펴보겠습니다.
## ~/project/string_sets.py
string_set = {"apple", "banana", "cherry", "apple"}
print(string_set)
파일을 저장하고 다시 실행합니다.
python ~/project/string_sets.py
출력은 다음과 같습니다.
{'cherry', 'banana', 'apple'}
중복된 "apple"이 자동으로 제거되었음을 알 수 있습니다. 집합은 고유한 요소만 저장합니다.
다음으로, 몇 가지 일반적인 집합 연산을 살펴보겠습니다. 두 개의 집합을 만들고 합집합과 교집합 연산을 수행합니다.
## ~/project/string_sets.py
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "fig"}
## Union of two sets
union_set = set1.union(set2)
print("Union:", union_set)
## Intersection of two sets
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)
파일을 저장하고 실행합니다.
python ~/project/string_sets.py
출력은 다음과 같습니다.
Union: {'cherry', 'banana', 'date', 'apple', 'fig'}
Intersection: {'banana'}
두 집합의 합집합은 두 집합의 모든 고유한 요소를 포함합니다. 교집합은 두 집합 모두에 공통적으로 포함된 요소만 포함합니다.