-
[Python]_42일차_06.17카테고리 없음 2021. 6. 17. 22:39
본 내용은 '2021년 혁신성장 청년인재 집중양성 사업'의 ‘인공지능 개발자 양성 과정’
강좌를 수강하면서 강의 및 강의노트를 참고하여 작성한 내용입니다.
Dictionary (딕셔너리)
특징
키 중복 불가능
소스코드
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict["brand"]) # Ford print(len(thisdict)) # items 개수 x = thisdict["model"] # value 값 x = thisdict.get("model") # value 값 동일 x = thisdict.keys() # dict_keys(['brand', 'model', 'year']) === 딕셔너리 아이템 값이 바뀜에 따라 업데이트 된다 (객체를 받아오기 때문) === car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.keys() print(x) # dict_keys(['brand', 'model', 'year']) car["color"] = "white" print(x) # dict_keys(['brand', 'model', 'year', 'color']) thisdict["year"] = 2018 # Change Values thisdict.update({"year": 2020}) # 다른 예 ===Adding Items thisdict["color"] = "red" thisdict.update({"color": "red"}) ===Removing Items thisdict.pop("model") thisdict.popitem() del thisdict["model"] del thisdict thisdict.clear() ===Loop Dictionaries for x in thisdict: # keys for x in thisdict: # values print(thisdict[x]) for x in thisdict.values(): print(x) for x in thisdict.keys(): print(x) for x, y in thisdict.items(): print(x, y) ===Copy a Dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = thisdict.copy() # 원본과 다른 객체이다!! print(mydict) mydict = dict(thisdict) # 원본과 다른 객체이다!! print(mydict) ===Nested Dictionaries myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } https://www.w3schools.com/python/python_dictionaries_loop.asp
Atom의 오류
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = dict(thisdict) #TypeError: 'dict' object is not callable print(mydict)
메소드 목록
if - else
a = 2 b = 330 print("A") if a > b else print("B")
While Loops
For Loops
Functions
오류
def my_function(fname, lname): print(fname + " " + lname) my_function("Emil") # 1개만 인자를 넣어서 오류
가변 인자 (튜플 형식)
def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus")
키워드 인자
def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
가변 키워드 인자 (딕셔너리 형식)
def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes") # key-value 형태
Default 매개변수 값
def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil")
파이썬의 Comprehension 소개 + Generator Expression
- https://mingrammer.com/introduce-comprehension-of-python/
- https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python
- http://schoolofweb.net/blog/posts/파이썬-제너레이터-generator/
non_squars = [x for x in range(101) if sqrt(x)**2 != x]
정규화란?
- 데이터를 일정한 규칙에 따라 변형하여 이용하기 쉽게 만드는 일
Generator을 사용하면 왜 동작 시간이 획기적으로 줄어드는가?
Generator 이란?
- 반복자와 같은 역할을 하는 함수
- (하나의 일을 마치면 자기가 했던 일을 기억하면서 대기하고 있다가 다시 호출되면 전의 일을 계속 이어서 하는 똑똑한 함수) → 일반 함수보다 훨씬 좋은 퍼포먼스 + 메모리 리소스 절약
next()
함수로 다음 값 반환- 일반적인 반복자와의 차이
- 일반적인 반복자
- 한번에 모든 값을 포함한 배열을 만들어서 리턴
- 제너레이터
- ★ 모든 결과값을 메모리에 저장하지 않는다 → 더 좋은 퍼포먼스
- yield 구문 → 한 번 호출될 때마다 하나의 값만을 리턴 → 일반 반복자에 비해 아주 작은 메모리 사용
- 일반적인 반복자
소스코드 예제
# 리스트 생성 및 반환 def square_numbers(nums): result = [] for i in nums: result.append(i * i) return result my_nums = square_numbers([1, 2, 3, 4, 5]) print my_nums # 제너레이터 사용 def square_numbers(nums): for i in nums: yield i * i my_nums = square_numbers([1, 2, 3, 4, 5]) #1 print my_nums =========================================== # List Comprehension my_nums = [x*x for x in [1, 2, 3, 4, 5]] print my_nums for num in my_nums: print num # 제너레이터 사용 my_nums = (x*x for x in [1, 2, 3, 4, 5]) #1 print my_nums for num in my_nums: print num ==================================================== def people_list(num_people): result = [] for i in xrange(num_people): person = { 'id': i, 'name': random.choice(names), 'major': random.choice(majors) } result.append(person) return result def people_generator(num_people): for i in xrange(num_people): person = { 'id': i, 'name': random.choice(names), 'major': random.choice(majors) } yield person
라이브러리 ↔ 패키지 ↔ 모듈
- 라이브러리 == 모호
- 패키지 == 폴더
- 모듈 == 파일
Atom 설치
- https://github.com/atom/atom/releases/tag/v1.57.0
- atom-x64-windows.zip
Atom을 설치하는 이유
Atom에는 hydrogen 패키지가 있다
- atom 내부에서 Jupyter kernel을 인식하여 python 코드 실행을 가능케 한다.
- Atom에서 hydrogen을 통해 python과 R을 실행할 수 있다.
추가 패키지 설치 목록
autocomplete-python 설치
Hydrogen 설치 : https://lelecoder.com/99
Run : Shift + Enter
Run : Ctrl + Enter
Clear Result : Ctrl + Shift + Backspace
minimap 설치
atom-file-icons 설치
highlight-seleted 설치 : https://the-illusionist.me/45
atom-beautify 설치
Ctrl + Alt + B
terminus (A fork of platformio-atom-ide-terminal) 설치 : https://atom.io/packages/terminus
화면 왼쪽 하단 + 기호 : Ctrl + `
platformio-ide-terminal 설치 : https://atom.io/packages/platformio-ide-terminal
platformio-ide-terminal package is no longer maintained.
Please uninstall platformio-ide-terminal and install either terminus or x-terminalhttps://github.com/platformio/platformio-atom-ide-terminal/issues/893
PyPy vs CPython
바로가기
간단히 말하면 CPython 은 일반적인 인터프리터인데 반해 PyPy 는 실행 추적 JIT(Just In Time) 컴파일을 제공하는 인터프리터기 때문이다. PyPy 는 RPython 으로 컴파일된 인터프리터인데, C 로 작성된 RPython 툴체인으로 인터프리터 소스에 JIT 컴파일을 위한 힌트를 추가해 CPython 보다 빠른 실행 속도를 가질 수 있게 되었다.
실제로 PyPy가 하는 일은 크게 두 가지이다.
RPython 언어로 동적 언어의 인터프리터를 구현할 수 있게 해주는 프레임워크
RPython으로 구현된 Python
JIT (Just-In-Time)
동적 번역(dynamic translation)은 프로그램을 실제 실행하는 시점에 기계어로 번역하는 컴파일 기법이다. 이 기법은 프로그램의 실행 속도를 빠르게 하기 위해 사용된다.
인터프리터 방식과 비교
인터프리터
바이트코드 명령어를 하나씩 읽어서 해석하고 실행한다. 하나씩 해석하고 실행하기 때문에 바이트코드 하나하나의 해석은 빠른 대신 인터프리팅 결과의 실행은 느리다는 단점을 가지고 있다.
흔히 얘기하는 인터프리터 언어의 단점을 그대로 가지는 것이다. 즉, 바이트코드라는 ‘언어’는 기본적으로 인터프리터 방식으로 동작한다. (python 과 동치)
JIT(Just-In-Time) 컴파일러
인터프리터의 단점을 보완하기 위해 도입된 것이 JIT 컴파일러이다. 인터프리터 방식으로 실행하다가 적절한 시점에 바이트코드 전체를 컴파일하여 네이티브 코드로 변경하고, 이후에는 해당 메서드를 더 이상 인터프리팅하지 않고 네이티브 코드로 직접 실행하는 방식이다.
네이티브 코드를 실행하는 것이 하나씩 인터프리팅하는 것보다 빠르고, 네이티브 코드는 캐시에 보관하기 때문에 한 번 컴파일된 코드는 계속 빠르게 수행되게 된다. (pypy 와 동치)