5.4. Sets

집합



Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
파이썬에는 집합이라는 데이터 유형도 있습니다. 집합에는 항목의 순서가 정해져 있지 않고, 중복되는 항목 역시 존재하지 않습니다. 기본적으로 구성원 테스트, 중복 항목 제거에 사용됩니다. 집합은 수학적 계산을 지원합니다. 조합, 교차, difference, symmetric difference 등을 말입니다.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.
중괄호 { } 또는 set()함수를 이용하여 집합을 만들 수 있습니다. 비어있는 집합을 만들 때는 set() 함수를 이용하고 { }를 사용하면 안됩니다. 중괄호 { }는 빈 딕셔너리(사전 자료형)를 만드는데 이용되는 기호이기 때문입니다. 딕셔너리는 다음 장에서 배우게 됩니다.

Here is a brief demonstration:
집합의 간단한 예를 한 번 살펴보겠습니다.

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # 중복된 항목이 사라지는 것에 주목하십시오.
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # 멤버 확인이 편리합니다.
>>> 'crabgrass' in basket
False

>>> # 두 개의 특이한 단어를 가지고 집합을 테스트 해보겠습니다.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # a 안에 들어있는 글자들이 하나씩 나타납니다. (중복된 글자는 사라짐)
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in either a or b : a와 b 합침 (중복글자 제외)
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # a와 b 양쪽에 모두 있는 글자
{'a', 'c'}
>>> a ^ b                              # 서로 겹치지 않는 글자
{'r', 'd', 'b', 'm', 'z', 'l'}

Similarly to list comprehensions, set comprehensions are also supported:
List Comprehension 이 가능한 것처럼, Set Comprehension 역시 가능합니다.

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

results matching ""

    No results matching ""