본문 바로가기

Python/Intermediate

(18)
[Python] 고급 - Dict 및 Set(2) - Sequence(4) Immutable Dict # immutable Dictfrom types import MappingProxyTyped = {'key1': 'value1'}f = dprint('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_frozen) # is..
[Python] 고급 - Dict 및 Set(1) - Sequence(3) 해시테이블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) - Sequence(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, bprint(divmod(100, 9))print(divmod(*(100, 9)))p..
[Python] 고급 - 리스트 및 튜플(1) - Sequence(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 Listschars = '+_)(*&^%$#@!~)'code_list1 = []f..
[Python] NamedTuple - Magic Method(3) 일반적인 tuple과 namedtupel 사용방법일반적인 tuple 사용시, 인덱스로 접근하므로 오류 가능성이 높고, 직관적이지 않다# 일반적인 튜플 사용from math import sqrtpt1 = (1.0, 5.0) # 변수 개수를 제한하는 구조로 설계불가. 네임드 튜플과 차이임.pt2 = (2.5, 1.5)l_leng1 = sqrt((pt2[0] - pt1[0]) ** 2 + (pt2[1] - pt1[1]) ** 2)print(l_leng1)# 3.8078865529319543# 네임드 튜플 사용from collections import namedtuple# 네임드 튜플 선언, 변수의 개수가 정해지므로 값을 3개 넣을수 없음Point = namedtuple('Point', 'x y')# 두 점 ..
[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) 워밍업 # 참조 : https://docs.python.org/3/reference/datamodel.html#special-method-names# 클래스 안에서 정의할 수 있는 특별한(built-in) 매소드, 파이썬에 이미 정의된 함수들임.# 기본형 - 모두 클래스입니다.print(int)print(float)# # # 모든 속성 및 메소드 출력print(dir(int))print(dir(float))# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floord..
[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 : {} - ..