본문 바로가기

Python

(74)
[Python] List Comprehension list comprehension은 기존 list를 사용하여 간단히 다른 list를 만드는 기법이다. 즉, 리스트를 쉽게, 짧게 한 줄로 만들 수 있는 파이썬 문법이다. 일반적으로 for + append 보다 속도가 빠르다. 예시1 number = [] for i in range(10): number.append(i) print(number) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 위의 for + append를 list comprehension형태로 나타내면 다음과 같다. number = [i for i in range(10)] print(number) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 예시2 filter를 사용한 list comprehension이다. 조건(..
[Python] iterable과 iterator 1. Iterable iterable 객체: 반복 가능한 객체 대표적으로 iterable한 타입 - list, dict, set, str, bytes, tuple, range collections.iterable에 속한 instance인지의 확인을 통해 iterable 객체인지 판별할 수 있다. >>> import collections # iterable 한 타입 >>> var_list = [1, 3, 5, 7] >>> isinstance(var_list, collections.Iterable) True >>> var_dict = {"a": 1, "b":1} >>> isinstance(var_dict, collections.Iterable) True >>> var_set = {1, 3} >>> isins..
[Python] list 관련 메서드 1. append() 리스트에 원소를 하나 삽입할 때 사용한다. 사용법: 변수명.append() 시간 복잡도: O(1) 2. sort() 변수명.sort() -> 기본 정렬 기능으로 오름차순으로 정렬한다. 변수명.sort(reverse=True) -> 내림차순으로 정렬한다. 시간 복잡도: O(NlogN) 3. reverse() 리스트의 원소의 순서를 모두 뒤집어 놓는다. 사용법: 변수명.reverse() 시간 복잡도: O(N) 4. insert() 특정한 인덱스 위치에 원소를 삽입할 때 사용한다. 사용법: insert(삽입할 위치 인덱스, 삽입할 값) 시간 복잡도: O(N) 5. count() 리스트에서 특정한 값을 가지는 데이터의 개수를 셀 때 사용한다. 사용법: 변수명.count(특정 값) 시간 복잡..
[Python] Object Oriented Programming(OOP) Object-Oriented Programming(OOP) 객체는 실생활에서 일종의 물건으로 속성(Attribute)과 행동(Action)을 가진다. OOP는 이러한 객체 개념을 프로그램으로 표현한 것이다. 속성은 변수(variable), 행동은 함수(method)로 표현된다. 파이썬 역시 객체 지향 프로그램 언어이다. OOP는 설계도에 해당하는 클래스(class)와 실제 구현체인 인스턴스(instance)로 나뉜다. 클래스와 객체와 인스턴스의 차이는? 붕어빵에 비유하자면 Class : 붕어빵 틀 기계 (설계도) 객체 : 붕어빵에 들어가는 재료 인스턴스 : 틀에서 만들어진 붕어빵 각각의 실체 구조 실체 클래스 O X 객체 X O 인스턴스 O O class 선언하기 object는 python3에서 자동 상..
[Python] 'is'와 '=='의 차이 is는 변수가 같은 Object(객체)를 가리키면 True이고, ==는 변수가 같은 Value(값)을 가지면 True이다. 예시 a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] b = a c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] print(a==b, a is b) # True True print(a==c, a is c) # True False a와 b, 그리고 a와 c 모두 같은 값들을 가진 리스트이기 때문에 a==b와 a==c 모두 True a와 b는 같은 리스트 객체이기 때문에 True, 하지만 a와 c는 다른 객체이기 때문에 False 참고: https://twpower.github.io/117-difference-between..
pip install requirements.txt pip install -r requirements.txt 를 실행했을 때, 중간에 에러가 나면 바로 멈춰버린다. 대신에 cat requirements.txt | xargs -n 1 pip install 를 사용하면 pip install을 한줄씩 실행하는 효과가 있어서 에러가 나더라도 쭉쭉 실행이 가능하다
[Python] 주피터 노트북에서 셀에서 값을 연속적으로 출력하는 방법 InteractiveShell의 옵션 지정 InteractiveShell의 옵션을 지정하여 모두 출력되도록 할 수 있다 InteractiveShell.ast_node_interactivity : 'all' | 'last' | 'last_expr' | 'none' (기본값은 'last_expr') from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" 참고: https://financedata.github.io/posts/display-all-values-in-cell-jupyter-notebook.html
[Python] 문자(한글, 영문)와 숫자만 나기고 특수문자 제거하기 import re string = "abcdefㄱㄴㄷㄹㅁㅂ가나다라마바사12345[]{}().,!?'`~;:" re.sub('[^A-Za-z0-9가-힣]', '', string) # Out: 'abcdef가나다라마바사12345' 출처: https://signing.tistory.com/74 [끄적거림]