Python/학습내용정리
10.Pythonic way
엉덩이싸움
2024. 6. 9. 21:36
1. listcomprehension:
iterable객체를 for- loop에서 반복하여 한번씩 하나씩 요소를 반환하여 리스트 생성
newlist = [expression for 변수 in iterable (객체 if 조건식)]
lambda 와 map 함수를 이용한 코딩보다는 list comprehension을 지향
lambda function : 1회용의 간단 함수
lambda[매개변수들 ] : 표현식
= (lambda[매개변수들] : 표현식)(인자들)
ex.
def add(x, y): -> lambda x, y : x + y
return x + y
filter function
: iterable 객체의 요소들의 함수에 넣어 그 반환값이 참인 것만 묶어서 filter object로 반환
형식 - filter(적용시킬_함수, 반복가능 객체)
map function
: iterable 객체들의 요소들의 함수에 넣어 동시에 적용하여 map object로 반환
형식 - map(적용시킬함수, 반복가능한 객체)
ex.
map func + lamda fun -> make a 제곱갑 list
a = list(range(1, 8)]
square_a = list(map(lambda x: x**2, a))
print(square_a)
+ reduce 함수(not 내장함수, in a functools library)
ex. a = [1,2,3,4] // n = reduce(lambda x, y : x + y, a) -> (((1 + 2) + 3) + 4) = 10
반복자
- iterable
해당 객체 : 반복 가능한 객체 (list, dict, set, str, bytes, tuple, range)
- Iterator (반복자)
해당 객체 : 값을 차례대대로 꺼낼 수 있는객체
+ range()는 정수 객체만을 인자로 가진다.
내부적으로 for문은 객체의 __next__() 메소드를 호출하는 작업을 수행함
#반복자 클래스 정의
case. 1)
class OddCounter:
def __init__(self, n = 1):
self.n = n
def __iter__(self): //근데 이 부분이 없어도 잘 실행 가능
return self
def __next__(self): #special method
t = self.n //여기서 출력하는 것은 t이기 때문에 초기값인 t = 1 부터 출력
self.n += 2
return t
my_counter = OddCounter()
print(next(my_counter))
print(my_counter.__next__())
print(my_counter.__next__())
print(my_counter.__next__())
//따라서 3번 실행되므로 마지막 printer값은 7이지만 n = 9
case.2)
class OddCounter:
def __init__(self, n = 1):
self.n = n
def __iter__(self):
return self
def __next__(self): #special method
t = self.n
self.n += 2
return t
my_counter = OddCounter()
for x in my_counter: //위의 iter part가 없는 경우 iterable함을 명시해주지 않아서 오류 발생
if x > 20: # 반복종료 조건
break
print(x, end =' ')
case.3)
class OddCounter:
def __init__(self, n = 1):
self.n = n
def __iter__(self):
return self
def __next__(self): #special method
if self.n < 20:
t = self.n
self.n += 2
return t
raise StopIteration #조건을 만족하지 않으면 stopiteration을 raise함
my_counter = OddCounter()
for x in my_counter:
print(x, end =' ')
iterable한 객체를 위한 내장함수
- all() : 반복 가능한 항목들이 모두 참일 때 참을 반환함
- any() : 임의의 반복 가능한 항목 들 중에 참이 하나라도 있을 경우 True 반환
- bool() : 리스트에 원소가 있다면 return True, otherwise return False
- list()
- split() 메소드, join() 메소드
2. generator
: 모든 값을 메모리에 저장하는 것이 아니라 필요할 때마다 생성해서 반환(lazy evaluation = call - by need), space complexity를 고려시 이용, return -> yield를 이용하여 generator 객체 반환함