-
62 - (파이썬) map/filter 함수 구현study with Q - 파이썬 2024. 7. 3. 19:17
def ma_map(cb_m,list_m) : output = [] for yoso_m in list_m: output.append(cb_m(요소)) return output #filter def ma_filter(cb_f,list_f): output = [] for yoso_f in list_f: #어차피 bool을 리턴한다면 #if cb_f(yoso_f) == True: if cb_f(yoso_f): output.append(yoso_f) return output
참고로...
더보기return[콜백함수(표현식) for 표현식 in 리스트]를 사용하면 한 줄로 작성 가능함.
나중에 "제너레이터 표현식"이라는 이터레이터를 다루는데, return(콜백함수(표현식) for 표현식 in 리스트) 형태로 바꾸면 이터레이터가 됨.
def ma_map(cb_m,list_m) : output = [] for yoso_m in list_m: output.append(cb_m(yoso_m)) return output def square(number): return number**2 lm = [11,12,13,14,15] print(ma_map(square,lm)) >>> [121, 144, 169, 196, 225]
def ma_filter(cb_f,list_f): output = [] for yoso_f in list_f: #어차피 bool을 리턴한다면 #if cb_f(yoso_f) == True: if cb_f(yoso_f): output.append(yoso_f) return output def is_even(숫자아): return 숫자아 % 2 == 0 lf= [11,12,13,14,15] print(ma_filter(is_even,lf)) >>> [12, 14]
'study with Q - 파이썬' 카테고리의 다른 글
64 - (파이썬) 기본 파일 처리 (0) 2024.07.08 63 - (파이썬) 람다, key 키워드 매개변수 (0) 2024.07.03 61 - (파이썬) 콜백함수, map/filter 함수 (0) 2024.07.01 60 - (파이썬) 튜플, 이뮤터블 자료, 뮤터블 자료 (0) 2024.06.24 59 - (파이썬) 조기 리턴과 리스트 평탄화하는 재귀 함수 (0) 2024.06.23