-
TIL 2023.05.24내일배움캠프 2023. 5. 24. 18:42
itertols
collections
가변인자 <- 개발할 때 가변인자로 처리하면 바로 구현 되는 문제가 좀 있다.
람다 함수 < - 코테 준비하고 있어요? 모범답안 보면 람다 펑션 많이 사용 되죠?
itertools: 반복자(iterator) 관련 다양한 함수 제공
효율적인 루핑을 위한 이터레이터를 만드는 함수
https://docs.python.org/ko/3.8/library/itertools.html
프로젝트에서 유용하게 사용할 수 있을 법한 함수
count(): 지정된 값에서 시작한 시퀀스를 생성하는 함수
import itertools counter = itertools.count(start=5, step=2) for i in counter: if i > 10: break print(i, end=" ") >>>>>> 5 7 9
cycle(): 지정된 시퀀스를 무한히 반복하는 함수
colors = ['red', 'green', 'blue'] color_cycle = itertools.cycle(colors) for _ in range(9): print(next(color_cycle), end=" ") >>>>>> red green blue red green blue red green blue
repeat(): 지정된 값을 지정된 횟수만큼 반복하는 함수
repeater = itertools.repeat("Hello", 5) for elem in repeater: print(elem, end=" ") >>>>>> Hello Hello Hello Hello Hello
chain(): 두 개 이상의 시퀀스를 연결하는 함수
permutations(): 지정된 시퀀스의 모든 가능한 순열을 생성하는 함수
combinations(): 지정된 시퀀스의 모든 가능한 조합(중복없음)을 생성하는 함수
순열 = 순서가 있는 조합
조합 - 순서개념이 없는 조합
perms = itertools.permutations([1, 2, 3], 2) for perm in perms: print(perm, end=" ") >>>>>> (1, 2) (1, 3) (2, 1) (2, 3) (3, 1) (3, 2) combs = itertools.combinations([1, 2, 3, 4], 3) for comb in combs: print(comb, end=" ") >>>>>> (1, 2, 3) (1, 2, 4) (1, 3, 4) (2, 3, 4)
accumulate(): 시퀀스의 누적 합계를 계산하는 함수
islice(): 지정된 요소를 포함하는 시퀀스를 생성하는 함수
islice(iterable객체, [시작], 정지[,stop])
collections: 컨테이너 클래스
https://docs.python.org/ko/3/library/collections.html
counter(): Counter 클래스는 해시 가능한 객체의 개수를 세는데 사용되는 특별한 딕셔너리 기본 자료형의 +@ 느낌
from collections import Counter fruit_count = Counter(['apple', 'apple', 'banana', 'apple', 'orange', 'banana']) print(fruit_count) >>>>>> Counter({'apple': 3, 'banana': 2, 'orange': 1}) print(sorted(fruit_count.elements())) # 개수만큼 반복되는 요소에 대한 이터레이터를 반환 >>>>>> ['apple', 'apple', 'apple', 'banana', 'banana', 'orange'] print(fruit_count.most_common(2)) # n 개의 가장 흔한 요소와 그 개수를 가장 흔한 것부터 가장 적은 것 순으로 나열한 리스트를 반환 >>>>>> [('apple', 3), ('banana', 2)]
defaultdict: 기본 값을 지정할 수 있는 특별한 딕셔너리 클래스
deque: deque 클래스는 양방향 큐(Double-ended Queue)
.append
.popleft
.pop
공식문서 볼 때 파이썬 버전 맞춰서 볼 것
다양한 파이썬 버전을 사용하기 위한 모듈 pyenv
가변인자
*args는 위치 인자를 임의의 개수로 받을 수 있는 매개변수
함수를 호출할 때 넣은 위치 인자들은 튜플로 묶여서 함수 내부로 전달
**kwargs는 키워드 인자를 임의의 개수로 받을 수 있는 매개변수
함수를 호출할 때 넣은 키워드 인자들은 딕셔너리로 묶여서 함수 내부로 전달
def add(*args): result = 0 for num in args: result += num return result def display_info(**kwargs): for key, value in kwargs.items(): print(key + ": " + value) def show_info(*args, **kwargs): print("Positional arguments: ") for arg in args: print(arg) print("\nKeyword arguments: ") for key, value in kwargs.items(): print(key + ": " + value) print(add(1, 2, 3)) >>>>>> 6 print(add(4, 5, 6, 7)) >>>>>> 22 display_info(name="Alice", age="25", country="USA") >>>>>> name: Alice age: 25 country: USA show_info(1, 2, 3, 4, 5, name="Alice", age="25", country="USA") >>>>>> Positional arguments: 1 2 3 4 5 Keyword arguments: name: Alice age: 25 country: USA
람다 함수
lambda 인자: 표현식
lambda: 람다 함수를 정의하기 위한 키워드
인자: 함수의 인자로 전달되는 값
표현식:
정렬: sort(key=lambda)
students = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 20}, {"name": "Charlie", "age": 30} ] students.sort(key=lambda student: student['age']) # 'age' 순으로 정렬 print(students) >>>>>> [{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]
필터링과 맵핑
2) map, filter
앞서 배운 제너레이터(`generator`)는 이터레이터(`iterator`) 입니다. 다만 제너레이터 표현식 또는 `yield`키워드를 통해 생성한 이터레이터는 구분을 위해서…
wikidocs.net
매핑
numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x**2, numbers)) # numbers에서 제곱 해서 담기 print(squared_numbers) >>>>>> [1, 4, 9, 16, 25]
필터링
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # numbers 에서 짝수만 담기 print(even_numbers) >>>>>> [2, 4, 6, 8, 10]
'내일배움캠프' 카테고리의 다른 글
TIL 2023.05.26 (0) 2023.05.26 TIL 2023.05.25 (0) 2023.05.25 TIL 2023.05.23 (0) 2023.05.23 TIL 2023.05.22 (0) 2023.05.22 WIL 내일배움캠프 10주차 (0) 2023.05.19