Table of Contents
파이썬 기초편 4강. 파이썬 집합형 자료구조 #
실습코드 #
사전 (Dictionary) #
#!python
# 빈 사전 생성
>>> d = {}
# 사전 생성
>>> d = {'A': 50, 'B': 54, 'C': 93}
# value에 리스트도 넣을 수 있음
>>> d = {'A': [34, 65], 'B': 43}
# value에 사전도 넣을 수 있음
>>> d = {'A': {'one': 1, 'two': 2}, 'B': [1, 2, 3]}
# dict()를 이용하여 사전 생성
>>> d = dict([('A', 50), ('B', 54), ('C', 93)])
>>> d
{'B': 54, 'C': 93, 'A': 50}
>>> d = dict(A=50, B=54, C=93)
사전 요소 접근 하기 #
#!python
>>> d['A']
50
>>> d['B']
54
# 없는 key로 접근할 경우 에러 발생
>>> d['D']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'D'
사전 요소 추가, 삭제 하기 #
#!python
# 'D' 추가
>>> d['D'] = 'New element'
>>> d
{'B': 54, 'C': 93, 'A': 50, 'D': 'New element'}
# 'D'의 value 변경
>>> d['D'] = 'Changed'
>>> d
{'B': 54, 'C': 93, 'A': 50, 'D': 'Changed'}
# 요소 삭제
>>> del d['D']
>>> d
{'B': 54, 'C': 93, 'A': 50}
사전에서 제공하는 다양한 기능 #
.keys() #
#!python
>>> d = {'B': 54, 'C': 93, 'A': 50}
>>> d.keys()
dict_keys(['B', 'C', 'A'])
# dict_key 타입으로 반환되므로 list()를 통해 리스트로 변환
>>> list(d.keys())
['B', 'C', 'A']]
# list(사전)으로도 key값의 리스트를 얻을 수 있음
>>> list(d)
['B', 'C', 'A']
.values() #
#!python
>>> d = {'B': 54, 'C': 93, 'A': 50}
>>> d.values()
dict_values([54, 93, 50])
>>> list(d.values())
[54, 93, 50]
.items() #
#!python
>>> d = {'B': 54, 'C': 93, 'A': 50}
>>> d.items()
dict_items([('B', 54), ('C', 93), ('A', 50)])
>>> list(d.items())
[('B', 54), ('C', 93), ('A', 50)]
.get(key, default) #
#!python
>>> d = {'B': 54, 'C': 93, 'A': 50}
>>> d.get('C', 'novalue')
93
>>> d.get('Q', 'novalue')
'novalue'
.setdefault(key, default) #
#!python
>>> d.setdefault('A', 'novalue')
50
>>> d
{'B': 54, 'C': 93, 'A': 50}
>>> d.setdefault('Q', 'novalue')
'novalue'
>>> d
{'B': 54, 'C': 93, 'A': 50, 'Q': 'novalue'}
dict1.update(dict2) #
#!python
>>> d = {'B': 54, 'C': 93, 'A': 50}
>>> d1 = {'E': 400, 'F': 22}
>>> d.update(d1)
>>> d
{'C': 93, 'Q': 'novalue', 'F': 22, 'B': 'TT', 'E': 400, 'A': 50}
세트 (Set) #
#!python
# 빈 세트 생성
>>> a = set()
>>> a
set()
# 정수로 이루어진 세트 생성
>>> a = set([1, 2, 3, 4])
>>> a
{1, 2, 3, 4}
# 혼합된 자료형으로 이루어진 세트생성
>>> a = set(['Green', 'Blue', 140, 50.3])
>>> a
{'Blue', 50.3, 140, 'Green'}
# 세트는 중복을 허용하지 않음
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a
{1, 2, 3, 4, 5, 6, 10}
>>> type(a)
<class 'set'>
# set()대신 {}를 사용해도 됨
>>> x = {1, 2, 3, 4, 5}
>>> type(x)
<class 'set'>
세트 값 추가 #
.add(val) #
#!python
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a
{1, 2, 3, 4, 5, 6, 10}
>>> a.add('A')
>>> a
{1, 2, 3, 4, 5, 6, 10, 'A'}
.update() #
#!python
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a.update(['A', 'B', 'C'])
>>> a
{1, 2, 3, 4, 5, 6, 'C', 'B', 10, 'A'}
# 여러 리스트와 사전을 동시에 추가할 수 있음
>>> b = set(['new', 'items', 'here'])
>>> c = [1, 100, 1000, 'new']
>>> a.update(b, c)
>>>
>>> a
{'items', 1, 'C', 3, 4, 5, 6, 2, 'here', 'B', 10, 100, 1000, 'new', 'A'}
세트 값 삭제 #
.remove(val) #
#!python
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a.remove(1)
>>> a
{2, 3, 4, 5, 6, 10}
# 없는 값을 삭제하면 KeyError 발생
>>> a.remove('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'A'
.clear() #
#!python
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a.clear()
>>> a
set()
.discard(val) #
#!python
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a.remove(1)
>>> a
{2, 3, 4, 5, 6, 10}
# 없는 값을 삭제해도 KeyError 발생안함
>>> a.discard('A')
.pop() #
#!python
>>> a = set(['Banana', 'Apple', 'Green', 'Blue'])
>>> a
{'Blue', 'Banana', 'Apple', 'Green'}
>>> a.pop()
'Blue'
>>> a.pop()
'Banana'
>>> a
{'Apple', 'Green'}
세트의 집합연산 #
합집합 #
#!python
>>> x = {1, 2, 3, 4, 5}
>>> y = {1, 2, 6, 7, 8}
>>> x | y
{1, 2, 3, 4, 5, 6, 7, 8}
>>> x.union(y)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> y.union(x)
{1, 2, 3, 4, 5, 6, 7, 8}
교집합 #
#!python
>>> x = {1, 2, 3, 4, 5}
>>> y = {1, 2, 6, 7, 8}
>>> x & y
{1, 2}
>>> x.intersection(y)
{1, 2}
>>> y.intersection(x)
{1, 2}
차집합 #
#!python
>>> x = {1, 2, 3, 4, 5}
>>> y = {1, 2, 6, 7, 8}
>>> x - y
{3, 4, 5}
>>> y - x
{8, 6, 7}
>>> x.difference(y)
{3, 4, 5}
>>> y.difference(x)
{8, 6, 7}}
여집합 #
#!python
>>> x = {1, 2, 3, 4, 5}
>>> y = {1, 2, 6, 7, 8}
>>> x ^ y
{3, 4, 5, 6, 7, 8}
>>> x.symmetric_difference(y)
{3, 4, 5, 6, 7, 8}
>>> y.symmetric_difference(x)
{3, 4, 5, 6, 7, 8}
세트에 제공하는 다양한 기능 #
.add(val) #
#!python
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a
{1, 2, 3, 4, 5, 6, 10}
>>> a.add('A')
>>> a
{1, 2, 3, 4, 5, 6, 10, 'A'}
frozenset() #
#!python
>>> a = frozenset([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a.add('B')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
.copy() #
#!python
>>> a = set([ 4, 5, 1, 2, 1, 3, 5, 6, 4, 10])
>>> a2 = a
>>> a1 = a.copy()
>>> a.clear()
>>> a1
{1, 2, 3, 4, 5, 6, 10}
>>> a2
set()
연습문제 #
1번 #
리스트 x = ['sheep', 'puppy', 'cat', ['dog', 'cow', 'pig'], 1, 3.22]
을 인덱싱, 슬라이싱, 다양한 기능 등을 사용하여 주어진 형태로 만드시오.
- ['dog', 'cow', 'pig']
- ['dog', 'cow']
- 3.22
- 'ee' (문자열 슬라이싱 이용)
- [['dog', 'cow', 'pig'], 1, 3.22]
- 3 (숫자형 형변환 이용)
- ['sheep', 'puppy', 'cat', ['dog', 'cow', 'piglet'], 1, 3.22]
2번 #
다음처럼 두 집합의 내용(공백으로 분리)을 입력받아, 합집합, 교집합, 차집합을 출력하는 프로그램을 작성하시오.
#!python
$ python3 set_operation.py
Set A: 1 2 3 4 5
Set B: 5 6 7 8 9
----
Union --> 1 2 3 4 5 6 7 8 9
Intersection --> 5
Diference --> 1 2 3 4
(힌트)
- 사용자로부터 입력을 받는 함수는 input 입니다.
- 공백 포함 문자열을 공백으로 나눈 리스트로 변환하려면 string.split() 메쏘드를 이용합니다.
연습문제 풀이 #
1번 #
#!python
>>> shop_category = {
'Beauty': [
'hair care', 'skin care', 'makeup',
'nail care', 'fragrances'],
'Clothing': [
'bags', 'coats', 'jacket', 'shorts',
'underwear', 'dresses'],
'Health': [
'vision care', 'vitamins',
'weigh management', 'oral care'],
'Electronics': [
'camera', 'car electronics', 'cell phones',
'computer', 'tablets', 'TV']
}
>>> shop_category.keys()
dict_keys(['Electronics', 'Clothing', 'Beauty', 'Health'])
>>> shop_category.values()
dict_values([['camera', 'car electronics', 'cell phones', 'computer', 'tablets', 'TV'], ['bags', 'coats', 'jacket', 'shorts', 'underwear', 'dresses'], ['hair care', 'skin care', 'makeup', 'nail care', 'fragrances'], ['vision care', 'vitamins', 'weigh management', 'oral care']])
>>> len(shop_category['Electronics'])
6
>>> shop_category['Beauty'].sort()
>>> shop_category['Electronics'].sort()
>>> shop_category['Clothing'].sort()
>>> shop_category['Health'].sort()
{'Electronics': ['TV', 'camera', 'car electronics', 'cell phones', 'computer', 'tablets'], 'Clothing': ['bags', 'coats', 'dresses', 'jacket', 'shorts', 'underwear'], 'Beauty': ['fragrances', 'hair care', 'makeup', 'nail care', 'skin care'], 'Health': ['oral care', 'vision care', 'vitamins', 'weigh management']}
2번 #
#!python
# set_operation.py
a = input('Set A: ')
b = input('Set B: ')
set_a = set(a.split())
set_b = set(b.split())
print('Union -->', set_a | set_b)
print('Intersection -->', set_a & set_b)
print('Difference -->', set_a - set_b)