본문 바로가기

Languages/Python

(16)
[파이썬 101] string 외장 및 내장 모듈 (문자열) 문자열 상수 (외장 string 라이브러리) 상수 (string.constant) 설명 예시 ascii_letters ascii_lowercase + ascii_uppercase 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_lowercase 영어 소문자 "abcdefghijklmnopqrstuvwxyz" ascii_uppercase 영어 대문자 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" digits 10진법 digits "0123456789" hexdigits 16진법 digits "0123456789ABCDEF" octdigits 8진법 digits "01234567" punctuation 특수기호 "!"#$%&'()*+,-./:..
[파이썬 라이브러리] itertools 모듈의 함수들 함수 정리 함수 파라미터 설명 accumulate iterable[, func, *, initial=None] - 누적 합계를 반환하는 이터레이터를 반환 - func에 합계 대신 다른 함수를 넣을 수 있음 chain *iterables - 여러 iterable을 연달아 반환 chain.from_iterable iterable - iterable을 여러개 받는 대신, iterable의 요소를 iterable로 combinations iterable, r - 조합 - 튜플 형태로 반환 combinations_with_replacement iterable, r - 중복조합 - 튜플 형태로 반환 compress data, selectors - selectors가 true인 인덱스의 data만 반환 - 둘다 it..
[파이썬 라이브러리] heapq 힙 큐 (heap queue) - 힙큐(heap queue) = 우선순위 큐 (priority queue) - heapq에서는 요소를 0부터 세서, heap[k]의 left-child는 heap[2*k+1], right-child는 heap[2*k+2]이다. >>> 1부터 만들면 편하지만, 파이썬은 0부터 - heapq의 heap은 기본적으로 최소힙(min heap) - 기본적으로 list를 사용함 heaq 함수 함수 파라미터 설명 heappush heap, item item을 heap으로 푸시 heappop heap pop 하고 반환. 빈 힙이면 IndexError heappushpop heap, item item을 push하고 가장 작은 항목을 pop (함수 두개 보다 효율적) heapify x 리스..
[파이썬 101] all과 any all(iterable) def all(iterable): for element in iterable: if not element: return False return True print(all([1, 2, 3, 4, 5])) print(all([1, True])) print(all([1, True, 0])) print(all([1, True, False])) print(all(range(10))) print(all(range(1, 10))) print(all([])) - 모든 요소가 참이면 True 반환. (하나라도 False면 False) - 비어 있으면 True (즉, False를 찾았을 때만 False 인듯) any(iterable) def any(iterable): for element in i..
[파이썬 101] List, Set, Dictionary 연산과 메서드의 시간복잡도 List 연산/메서드 의 시간복잡도 연산 / 메서드 예시 복잡도 비고 Index list[i] O(1) Store list[i] = value O(1) Length len(list) O(1) Append list.append(value) O(1) Pop list.pop() O(1) list.pop(-1) Clear list.clear() O(1) list = list(), list= [] Slice list[a:b] O(b-a) slicing 되는 개수에 비례 : O(N) Extend list.extend(other_list) O(len(...)) other_list의 크기에 비례 : O(N) Construction list() O(len(...)) 초기화되는 크기에 비례 : O(N) Equality l..
[파이썬 라이브러리] Collections 모듈의 deque (데크, 덱, 디큐, 데큐) deque from collections import deque myList = [1, 2, 3, 4, 5] myDict = {'one': 1, 'two': 2, 'three': 3} myDeque = deque() print(type(myDeque)) print(myDeque) print(deque(myList)) print(deque(myDict)) print(deque(myDict.values())) - deque([iterable[, maxlen]]) - iterable을 넣어주지 않으면 빈 큐를 반환 - 데크, 덱, 디큐, 데큐 등으로 불림 - deque = double-ended-queue = 양방향 큐 - 양쪽 끝에서 append와 pop 등을 O(1) 성능으로 지원 (list의 경우 pop..
[파이썬 라이브러리] functools 모듈의 reduce 메서드 reduce() def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: value = next(it) else: value = initializer for element in it: value = function(value, element) return value - reduce(function, iterable[, initializer=None]) - reduce(함수, 이터러블, 최기값) - 위 코드는 reduce 메서드를 나타낸 코드 - lambda 이용시 첫번째 인자가 누적값(직전 실행의 결과값), 두번째 인자가 새로운 값 - 첫번째 인자를 accumulation(acc), 두번째 인자..
[파이썬 101] lambda (람다) 조건부 표현식 사용하기 myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(map(lambda n: str(n) if n % 2 else n, myList))) print(list(map(lambda n: str(n) if n % 2 else float(n) if n % 3 else n, myList))) - elif 사용 불가 (if-else 는 중첩 가능) - elif가 필요할 경우 함수를 만드는 것을 권장 참조 - 코딩 도장
[파이썬 101] map 함수 (Iterator, Iterable) Iterable myList = [1, 2, 3, 4, 5] myDict = {'name': '홍길동', 'age': 28, 'gender': 'male'} myStr = 'Hello World!' myRange = range(10) for item in iter(myList): print(item, end=' / ') print() for item in myDict: print(item, end=' / ') print() for item in myStr: print(item, end=' / ') print() for item in myRange: print(item, end=' / ') print() - iterable 객체 : 반복 가능한 객체 - Iterable : list, dictionary, ..
[파이썬 101] re 모듈 (함수, 플래그, 일치 객체) 플래그 플래그 설명 re.A re.ASCII 유니코드 대신 ASCII 전용 일치 수행 re.U re.UNICODE 유니코드 일치. (파이썬3에서는 default이므로 필요 없음) re.DEBUG 컴파일된 정규식에 대한 디버그 정보 표시 re.I re.IGNORECASE 대소문자를 구분하지 않는 일치 re.L re.LOCALE 특정 일치를 로케일에 의존하도록 함 (권장 X) re.M re.MULTILINE '^'와 '$'에서 기준을 줄바꿈 단위로 일치 (문자열 시작, 문자열 끝, 개행 전후) re.S re.DOTALL '.' 가 줄넘김을 포함하여 모든 문자와 일치하도록 함 (default : 개행을 제외한 모든 문자) re.X re.VERBOSE 채턴 내 공백 무시 (주석으로 더 직관적인 코드를 작성할때 ..

반응형