집합(순서 없음, 논리 연산 최적화)

Python의 데이터 타입

Jason Myers

Instructor

집합 (Set)

  • 유일함
  • 순서 없음
  • 가변형
  • 수학의 집합 이론을 Python에 구현
Python의 데이터 타입

집합 생성하기

  • 리스트로부터 집합을 생성합니다
cookies_eaten_today = ['chocolate chip', 'peanut butter', 
   ...: 'chocolate chip', 'oatmeal cream', 'chocolate chip']

types_of_cookies_eaten = set(cookies_eaten_today)
print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter'])
Python의 데이터 타입

집합 수정하기

  • .add()는 단일 원소를 추가합니다
types_of_cookies_eaten.add('biscotti')

types_of_cookies_eaten.add('chocolate chip')

print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter', 'biscotti'])
Python의 데이터 타입

집합 업데이트

  • .update()는 다른 집합이나 리스트를 병합합니다
cookies_hugo_ate = ['chocolate chip', 'anzac']

types_of_cookies_eaten.update(cookies_hugo_ate)

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream',  'peanut butter', 'biscotti'])
Python의 데이터 타입

집합에서 데이터 제거

  • .discard()는 값으로 안전하게 제거합니다
  • .pop()은 임의의 원소를 제거하고 반환합니다(비면 KeyError)
types_of_cookies_eaten.discard('biscotti')

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
types_of_cookies_eaten.pop()
types_of_cookies_eaten.pop()
'chocolate chip'
'anzac'
Python의 데이터 타입

집합 연산 - 공통점

  • .union()은 두 집합의 합집합을 반환합니다 (or)
  • .intersection()은 공통 원소를 찾습니다 (and)
cookies_jason_ate = set(['chocolate chip', 'oatmeal cream',
'peanut butter'])
cookies_hugo_ate = set(['chocolate chip', 'anzac'])

cookies_jason_ate.union(cookies_hugo_ate)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
cookies_jason_ate.intersection(cookies_hugo_ate)
set(['chocolate chip'])
Python의 데이터 타입

집합 연산 - 차이점

  • .difference()는 기준 집합에는 있고 인자에는 없는 원소를 찾습니다 (-)
  • 기준(타깃)을 정확히 지정해야 합니다!
cookies_jason_ate.difference(cookies_hugo_ate)
set(['oatmeal cream', 'peanut butter'])
cookies_hugo_ate.difference(cookies_jason_ate)
set(['anzac'])
Python의 데이터 타입

Ayo berlatih!

Python의 데이터 타입

Preparing Video For Download...