본문 바로가기

Python/중급

(18)
[Python] 고급 - Dict 및 Set(2) Immutable Dict # immutable Dict from types import MappingProxyType d = {'key1': 'value1'} f = d print('f = d : ', d is f, d == f) # is 는 id 가 같은지 확인, == 는 값이 같은지 확인 print('value & id: ', d, id(d)) print('value & id: ', f, id(f)) print() # Read Only(Immutable Dict 생성) d_frozen = MappingProxyType(d) print(d, id(d), type(d)) print(d_frozen, id(d_frozen), type(d_frozen)) print(d is d_frozen, d == d_..
[Python] 고급 - Dict 및 Set(1) 해시테이블 Key에 Value 를 저장하는 구조 파이썬 dict 해쉬 테이블 예 키 값의 연산 결과에 따라 직접 접근이 가능한 구조 key 값을 해싱함수 -> 해쉬주소 -> key 에 대한 value 참조 # Dict 구조 # print(__builtins__.__dict__) # Hash 값 확인 t1 = (10, 20, (30, 40, 50)) t2 = (10, 20, [30, 40, 50]) print(hash(t1)) # 오류 발생 print(hash(t2)) # 리스트는 변경가능하므로 해쉬값을 확인 불가능함. --------------------------------------------[result] 5737367089334957572 --------------------------------..
[Python] 고급 - 리스트 및 튜플(2) 컨테이너 타입 자료형(Container : 서로다른 자료형[list, tuple, collections.deque], a = [3, 3.5, 'a'] # 서로 다른 자료형, 컨네이너 타입 자료형 Flat : 한 개의 자료형[str, bytes, bytearray, array.array, memoryview]) 한개의 자료형만 저장, 빠름, 자연어 처리, 숫자, 이산, 회계분석, 기상데이터 등 단일 형태의 연산 가변(list, bytearray, array.array, memoryview, deque) 불변(tuple, str, bytes) unpacking # Tuple Advanced # Unpacking # b, a = a, b print(divmod(100, 9)) print(divmod(*(100..
[Python] 고급 - 리스트 및 튜플(1) 컨테이너 타입 자료형(Container : 서로다른 자료형[list, tuple, collections.deque], a = [3, 3.5, 'a'] # 서로 다른 자료형, 컨네이너 타입 자료형 Flat : 한 개의 자료형[str, bytes, bytearray, array.array, memoryview]) 한개의 자료형만 저장, 빠름, 자연어 처리, 숫자, 이산, 회계분석, 기상데이터 등 단일 형태의 연산 가변(list, bytearray, array.array, memoryview, deque) 불변(tuple, str, bytes) # 지능형 리스트(Comprehending Lists) # Non Comprehending Lists chars = '+_)(*&^%$#@!~)' code_list1 ..
[Python] NamedTuple 일반적인 tuple과 namedtupel 사용방법 일반적인 tuple 사용시, 인덱스로 접근하므로 오류 가능성이 높고, 직관적이지 않다 # 네임드 튜플 사용 from collections import namedtuple from math import sqrt # 일반적인 튜플 사용 pt1 = (1.0, 5.0) pt2 = (2.5, 1.5) # 일반적인 튜플 계산, 인덱스로 접근가능 l_leng1 = sqrt((pt2[0] - pt1[0]) ** 2 + (pt2[1] - pt1[1]) ** 2) # 네임드 튜플 선언 Point = namedtuple('Point', 'x y') # 두 점 선언 pt3 = Point(1.0, 5.0) pt4 = Point(2.5, 1.5) # 네임드 튜플 계산, 키값으로 ..
[Python] Magic Method(2) 클래스 샘플2 class Vector(object): def __init__(self, *args): # function Doctring '''(init)Create a vector, example : v = Vector(5,10)''' if len(args) == 0: self._x, self._y = 0, 0 else: self._x, self._y = args # un-packing def __repr__(self): '''(repr)Returns the vector infomations''' return '(repr)Vector(%r, %r)' % (self._x, self._y) def __add__(self, other): '''(add)Returns the vector addition of ..
[Python] Magic Method(1) 클래스 예제 class Fruit: def __init__(self, name, price): self._name = name self._price = price def __str__(self): return '(str)Fruit Class Info : {} , {}'.format(self._name, self._price) def __ge__(self, x): print('Called >> __ge__ Method.') if self._price >= x._price: return True else: return False def __le__(self, x): print('Called >> __le__ Method.') if self._price = s2) print(s1 > __ge__ Method...
[Python] Class(3) - Class Method, Static Method Instance method, Class method, Static method # 클래스 선언 class Car(object): ''' Car Class Author : Me Date : Description : Class, Static Method, Class Method ''' # Class Variable(모든 인스턴스가 공유 가능) price_per_raise = 1.0 def __init__(self, company, details): self._company = company self._details = details def __str__(self): return 'str : {} - {}'.format(self._company, self._details) def __repr__(self):..