728x90
반응형
집합(Set)
집합은 파이썬에서 제공하는 중요한 자료구조 중 하나로, 고유한 원소들로 이루어진 불변하고 순서 없는 컬렉션입니다.
집합은 수학적인 집합 개념을 파이썬에 적용한 것으로, 여러 가지 유용한 연산을 지원합니다.
그럼 자세히 알아보도록 하겠습니다.
1. 집합의 생성
파이썬에서 집합을 생성하기 위해서는 중괄호({})를 사용합니다.
예를 들어, 다음과 같이 집합을 생성할 수 있습니다.
fruits = {'apple', 'banana', 'orange'}
또는 `set()` 함수를 사용하여 집합을 생성할 수도 있습니다.
fruits = set(['apple', 'banana', 'orange'])
2. 집합의 특징
- 원소의 고유성
- 집합은 중복된 원소를 허용하지 않습니다. 동일한 원소가 여러 번 포함되더라도 한 번만 저장됩니다.
- 순서 없음
- 집합은 원소들이 순서 없이 저장되기 때문에 인덱스를 사용하여 원소에 접근할 수 없습니다.
3. 집합의 연산
- 합집합
- 두 집합의 모든 원소를 합쳐 새로운 집합을 생성합니다.
union_set = set1.union(set2)
- 교집합
- 두 집합에 공통으로 존재하는 원소로 이루어진 새로운 집합을 생성합니다.
intersection_set = set1.intersection(set2)
- 차집합
- 한 집합에는 속하고 다른 집합에는 속하지 않는 원소로 이루어진 새로운 집합을 생성합니다.
difference_set = set1.difference(set2)
4. 집합의 원소 추가 및 제거
- 원소추가
- `add()` 메소드를 사용하여 집합에 새로운 원소를 추가할 수 있습니다.
fruits.add('grape')
- 원소제거
- `remove()` 메소드를 사용하여 집합에서 원소를 제거할 수 있습니다. 제거하려는 원소가 집합에 없을 경우 `KeyError`가 발생하므로 `discard()` 메소드를 사용하면 안전합니다.
5. 집합의 크기와 원소 확인
- 크기확인
- `len()` 함수를 사용하여 집합의 크기를 확인할 수 있습니다.
size = len(fruits)
- 원소확인
- `in`산자를 사용하여 특정 원소가 집합에 속하는지 여부를 확인할 수 있습니다.
is_included = 'banana' in fruits
파이썬의 집합(Set)은 고유한 원소들로 이루어진 순서 없는 컬렉션입니다.
집합은 합집합, 교집합, 차집합 등 다양한 연산을 통해 유용한 작업을 수행할 수 있습니다.
잘못된 정보는 댓글로 알려주시면 감사하겠습니다.
728x90
반응형
'Python' 카테고리의 다른 글
Python - 13. 파이썬의 함수(Function)과 인수(argument). (0) | 2023.07.15 |
---|---|
Python - 12. 파이썬의 딕셔너리 (Dictionary) (0) | 2023.07.14 |
Python - 10. 파이썬에서 2차원 리스트/튜플 활용하기 (0) | 2023.07.12 |
Python - 9. 파이썬 튜플(tuple), 불변한(Immutable)한 자료구조. (0) | 2023.07.11 |
Python - 8. 리스트 내포(List Comprehension) (0) | 2023.07.10 |