본문 바로가기

웹_프론트_백엔드/Python

2020.01.20

1. lec05_dict.py

# -*- coding: utf-8 -*-
# dictionary 딕셔너리  기본, 심화 : 생성, 추가, in 
# 딕셔너리란 ? key와 value의 쌍으로 이루어진 데이터 형태. 
# 자바의 hashmap, JSON형태와 동일(자바스크립트)
# 키는 어떤타입이든 가능.int, str. 
# 순서없음. 시퀀스 아님. 인덱싱 안됨. 
# 키는 유일해야 함. (키=인덱싱 )

#빈 딕셔너리
com_dic = {}
print(com_dic, type(com_dic))
com_dic =dict()
print(com_dic, type(com_dic))

#딕셔너리 생성
com_dic = {'C' : '시스템 프로그래밍 언어', 
           'Python' : '데이터분석 언어',
           'Java'   : '모바일용 언어'
           }
print(com_dic, type(com_dic))

#딕셔너리로 변환 :키워드인자 -> dict() 
member_dict = dict(name='신상림', id=1111, login_date='2020/01/02')
print(member_dict, type(member_dict))

#딕셔너리로 변환  : list ->  dict()
prices= dict([ ['item_a', 100],  ['item_b', 200],  ['item_c', 300]])
print(prices)

#딕셔너리로 변환  : tuple ->  dict()
tuple_a = (('item_a', 100), ('item_b', 100), ('item_c', 100), ('item_c', 500))
#키가 중복되어도 에러가 나지 않고 overwrite이 될 뿐. 
tuple_prices = dict(tuple_a)
print(tuple_prices)

#딕셔너리로 변환  : zip(keys, values)을 사용하여 ->  dict()
# keys, values 는 키워드가 아님. 변수이름일 뿐. 
keys = ['item_a','item_b','item_c','item_d' ]
values =[100,200,300,400]
zip_prices = dict(zip(keys, values))
print(zip_prices)

#키로 값 가져오기 (읽기)
print(prices['item_a'])

#  item_a:2, item_b:3 총매출은 ? 
print(prices['item_a']*2+ prices['item_b']*3)

#추가/변경
print(prices)
#기존에 키가 있으면 변경(overwrite)
prices['item_a']=1000
print(prices)
#기존에 키가 없으면 추가 
prices['item_d']=6700
print(prices)

#키가 있는지 확인 : in (key확인 ) 
print('item_a'in prices)

#삭제  :del
del (prices['item_d'])
print(prices)

#모든 항목 삭제 
print(zip_prices)
zip_prices.clear()
print(zip_prices)

#dic 심화 
#항목얻기 : 키가 없을 때는 에러 발생
print(prices['item_f'])
value =prices.get('item_f') # None (없음)
print(value)
value =prices.get('item_f', 0 ) #default를 0으로 설정 
print(value)

#모든 키 얻기 
print(prices.keys())
#모든 값 얻기 
print(prices.values())
#키와 값 다 얻기 
print(prices.items())

2. lex05_dict.py

# -*- coding: utf-8 -*-
gdp_global = \
'''Rank	Name	2019 Population	GDP (IMF)	GDP (UN '16)	GDP Per Capita
1	UnitedStates	329,064,917	21,410,230	18,624,475	$65,064
2	China	1,433,783,686	15,543,710	11,218,281	$10,841
3	Japan	126,860,301	5,362,220	4,936,212	$42,269
4	Germany	83,517,045	4,416,800	3,477,796	$52,885
5	India	1,366,417,754	3,155,230	2,259,642	$2,309
6	France	65,129,728	3,060,070	2,465,454	$46,984
7	UnitedKingdom	67,530,172	3,022,580	2,647,899	$44,759
8	Italy	60,550,075	2,261,460	1,858,913	$37,349
9	Brazil	211,049,527	2,256,850	1,795,926	$10,693
10	Canada	37,411,047	1,908,530	1,529,760	$51,015
11	SouthKorea	51,225,308	1,777,650	1,411,246	$34,703
12	Russia	145,872,256	1,754,290	1,246,015	$12,026
'''

# gdp_global이 잘 저장됬나 출력해보기
print(gdp_global)

#1. 이스케이프 문자(\n, \t)를 함께 출력해보세요.
print(repr(gdp_global))

#2. 전체 몇 줄의 데이터가 있나요?
print(len(gdp_global.split('\n')))

#3. 한 줄에 몇 개의 데이터가 있나요?
lines = gdp_global.split('\n')
print(len(lines[0].split('\t')))
print(len(lines[1].split('\t')))

#4. gdp_global의 모든 '\n'을 모두 '\t'으로 바꾸세요
# 바꾼다음 gdp_global_tap으로 저장하세요
gdp_global_tap = gdp_global.replace('\n', '\t')
print(repr(gdp_global_tap)) 

#5. 4번을 가지고 첫째줄, 둘째줄, 셋째줄 데이터를 추출하세요. (슬라이싱 slicing)
#5.1 4번을 가지고 '\t'으로 split을 하여 리스트를 만드세요
gdp_global_by_tap = gdp_global_tap.split('\t')
print(gdp_global_by_tap)
#5.2 첫째줄, 둘째줄, 셋째줄 데이터를 추출, 기존에 첫번째 줄이 6개란 것을 확인했음, 그걸 이용하면 
print(gdp_global_by_tap[:6])
print(gdp_global_by_tap[6:12])
print(gdp_global_by_tap[12:18])

#6. 5번을 가지고 나라 이름만 추출해보세요(slicing)
keys = gdp_global_by_tap[7::6]
print(gdp_global_by_tap[7::6])

#7. 5번을 가지고 gdp(imf)만 추출해보세요(slicing)
values=gdp_global_by_tap[9::6]
print(gdp_global_by_tap[9::6])

#8. 6번(keys)과 7번(values)을 가지고 딕셔너리를 만들어보세요
gdp_imf = dict(zip(keys, values))
print(gdp_imf)

#9. sorting(나라이름 알파벳 순서로) 나라이름만 출력
print(sorted(gdp_imf))

#10. 나라이름과 gdp까지 정렬(나라이름 알파벳 순서로)
print(sorted(gdp_imf.items()))

#11. spain의 gdp를 구하되, 없으면 0을 출력하세요.
print(gdp_imf.get('spain', 0))

#12. Italy의 gdp를 구하되, 없으면 0을 출력하세요.
print(gdp_imf.get('Italy', 0))

3. lex06_set.py

# -*- coding: utf-8 -*-
# set 기본, 생성, 변환, in, add, 연산자(부분집합, 합집합, ......)
# set 집합 : 각 원소가 유일. 순서 없음. 중복을 제거할 때 유용함.
# dictionary에서 key(유일)가 집합이라고 생각할 수 있음.

# 빈 set 생성하기
set_a = set()
print(set_a, type(set_a))

# set 생성
set1 = {1, 3, 5, 7, 10}
print(set1, type(set1))

# set으로 변환
print(set('aabbeccdd')) #str -> set
print(list('aabbeccdd')) #비교
print(set(list('aabbeccdd'))) #list -> set
print(set((1,3,5,3,2,1,2,1))) #tuple -> set

# dic -> set : key만 남는다
dic_a = {'item_a' : 1000, 'item_b' : 200, 'item_c' : 300}
print(set(dic_a))

# 있는지 확인
print(1 in set1) 

# set에 추가
set1.add(100)
print(set1)

# 여러 개 추가
set1.update({4,2,9})
print(set1)

# 하나만 삭제
set1.remove(1)
print(set1)

# 모두 삭제
set1.clear()
print(set1)

# 연산자
set1 = {1,2,3,4,5}
set2 = {3,4,5,6,7,8,9,10}
# 교집합 : intersection(), &
print(set1 & set2)
print(set1.intersection(set2))
# 합집합 : union(), |
print(set1 | set2)
print(set1.union(set2))
# 차집합 : difference(), -
print(set1-set2)
print(set1.difference(set2))
# 서로소(exclusive OR), ^
print(set1^set2)
print(set1.symmetric_difference(set2))
 
a={2,3}
b={1,2,3}
# 부분집합인지 issubset(), <=
print(a<=b)
# 전체집합인지 issuperset(), >=
print(a>=b)

'웹_프론트_백엔드 > Python' 카테고리의 다른 글

2020.01.22  (0) 2020.01.22
2020.01.21  (0) 2020.01.22
2020.01.17  (0) 2020.01.19
2020.01.16  (0) 2020.01.17
2020.01.15  (0) 2020.01.16