Input/python

[python] 파이썬 공식홈페이지 set : 생성, 원소 추가 & 삭제

buji-learn 2023. 5. 11. 22:00

생성

  1. 중괄호 (  '{}', braces) 안에 쉼표 ( ',' ,  comma)로 분리된 원소들을 나열
  2. set comprehension 사용
  3. type 변환 명령어 사용
#1 원소 나열
set1 = {1, 2, 3, 4, 5}
print(set1)    # {1, 2, 3, 4, 5}

#2 set comprehension
square = [2, 4, 8, 16, 32, 64, 128, 256]
set2 = {num for num in square if num <= 100}
print(set2)    # {2, 4, 8, 16, 32, 64}

#3 타입 변환
sampleList = [10, 20, 30, 40, 50]
set3 = set(sampleList)     
print(set3)     # {10, 20, 30, 40, 50}

sampleStr = '1020304050'
set4 = set(sampleStr)
print(set4)     # {'0', '1', '2', '3', '4', '5'}

set에도 list처럼 comprehension이 있다는 것을 처음 알았다. 공식 문서로 공부하면 좋은 점이다.

 

update([set])

 

 

  1. update([list / set])  :  A + B + C
  2. intersection_update([list / set])  :  A
  3. difference_update([list / set])  :  B
  4. symmetric_difference_update([list / set])  : B + C

 

 

 

 

 

numbers = range(51)

# 4의 배수
set5 = {num for num in numbers if num%4 == 0}
# 6의 배수
set6 = {num for num in numbers if num%6 == 0}

test = set5.update(100)
# error 발생   >>  'int' object is not iterable

#1_ 4 또는 6의 배수
updat = set5.update(set6)
print(updat)     # None
# ...?   >>  반환 없음!!

set5.update(set6)
print(set5)    # {0, 5, 6, 10, 12, 15, 18, 20, 24, 25, 30, 35, 36, 40, 42, 45, 48, 50}

#2_ 4와 6의 공배수 = 12의 배수
set5 = {num for num in numbers if num%4 == 0}
set5.intersection_update(set6)
print(set5)    # {0, 12, 24, 36, 48}

#3_ 4의 배수이면서 6의 배수가 아닌 수
set5 = {num for num in numbers if num%4 == 0}
set5.difference_update(set6)
print(set5)    # {4, 8, 16, 20, 28, 32, 40, 44}

#4_ 4 또는 6의 배수이면서 12의 배수가 아닌 수
set5 = {num for num in numbers if num%4 == 0}
set5.difference_update(set6)
print(set5)    # {32, 4, 6, 8, 40, 42, 44, 16, 18, 20, 28, 30}

 

add(element)

seasons = {'spring', 'summer', 'autumn'}
seasons.add('winter')
print(seasons)    # {'autumn', 'spring', 'summer', 'winter'}

 

remove(element)

  • set 안에 제거하려는 원소가 없으면 KeyError 발생 
  • 반환 없음

discard(element)

  • set 안에 제거하려는 원소가 없어도 error 없음
  • 반환 없음
seasons.remove('spring')
print(seasons)    # {'autumn', 'summer', 'winter'}

seasons.discard('autumn')
print(seasons)    # {'summer', 'winter'}

seasons.remove('spring')
# error 발생   >> KeyError: 'spring'

seasons.discard('autumn')
print(seasons)    # {'summer', 'winter'}

 

pop(element)

  • set에서 '랜덤'으로 원소 제거
  • set이 비어있으면 KeyError 발생 
  • 제거된 값 반환
arbitrary = seasons.pop()

print(arbitrary)    # 'summer'
print(seasons)    # {'winter'}

# seasons 비어있을 때
seasons.pop()
# error 발생  >>  KeyError: 'pop from an empty set'

와우~! 오늘의 발견이다. 집합에서 pop을 사용하면 랜덤으로 원소가 반환된다. list와 달리, index가 없어서 가능한 듯 하다.

 

clear()

  • set에 있는 모든 element 삭제
  • 반환 없음
cities = {'Seoul', 'Daejeon', 'Daegu', 'Busan'}
print(cities)    # {'Busan', 'Daegu', 'Daejeon', 'Seoul'}
# 알파벳 순으로 정렬되는 건가?
# 물론 set에서 순서는 상관 없음

cities.clear()
print(cities)    # set()

 


Q. 왜 frozenset일까?

  • print(type(sampleSet)) 으로 set 타입을 출력하면  '<class 'set'>이라고 나온다.

 

Further. list 원소 다루는 키워드 정리하기