Python 개념정리-SET

DONGHYUN KOO·2020년 8월 22일
0

python

목록 보기
7/19

SET

  • List와 마찬가지로 여러 다양한 타입의 요소(element)들을 저장
  • List와 다르게 요소들이 순서대로 저장되어 있지 않습니다. 즉 ordering이 없다
  • 순서가 없으므로 indexing도 없습니다
  • 동일한 값을 가지고 있는 요소가 1개 이상 존재 할 수 없습니다.(동일한 값의 요소가 존재한다면 새로운 요소가 이 전 요소를 치환)

Set 생성하는 법

set1 = {1, 2, 3}
set2 = set([1, 2, 3])

set1 = {1, 2, 3, 1}
print(set1)
> {1, 2, 3}
set2  = set([1, 2, 3, 1])
print(set2)
> {1, 2, 3}``

**Set에서 요소 삭제하기**
Set에서 요소를 삭제할때는 remove 함수를 사용

> my_set = {1, 2, 3}
my_set.remove(3)
print(my_set)
# >> {1, 2}

Look Up

set에 어떠한 값이 이미 포함되어 있는지를 알아보는 것을 look up이라고 한다
set에서 look up을 사용하기 위해서는 in키워드를 사용해야한다

my_set = {1, 2, 3}

if 1 in my_set:
  print("1 is in the set")
## > 1 is in the set

if 4 not in my_set:
    print("4 is not in the set")
## > 4 is not in the set

Intersection (교집합) & Union (합집합)
set은 교집합(Intersection)과 합집합(Union)을 구할수 있다.

set의 교집합을 구할때는 & 키워드 또는 intersection()함수를 사용한다

set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}

print(set1 & set2)
# >> {4, 5, 6}

print(set1.intersection(set2))
# >> {4, 5, 6}
set의 합집합을 구할 때는 | 혹은 union()함수를 사용한다.

print(set1 | set2)
# >> {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.union(set2))
# >> {1, 2, 3, 4, 5, 6, 7, 8, 9}

0개의 댓글