본문 바로가기
Programming/Python

filter(), map()

by Chan_찬 2020. 10. 5.
728x90

python - filter,map

filter()

filter(function, list)는 시퀀스의 항목들 중 함수조건이 참(True)인 항목만 추출해 구선된 시퀀스를 반환한다

>>> def f(x): return x%2 != 0 and x%3 != 0
>>> f(33)
False
>>> f(17)
True
>>> list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
# 상동. list(), filter() 대신 사용
>>> r = [f(x) for x in range(2, 25)]
[5, 7, 11, 13, 17, 19, 23]

map()

map(function, list)는 시퀀스의 모든 항목에 함수를 적용한 결과리스트를 반환한다

>>> def cube(x): return x*x*x
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> seq = range(8)
>>> def square(x): return x*x
>>> list(zip(seq, map(sequare, seq))))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
# 상동. zip(), map() 대신 사용
>>> r = [(s, square(s)) for s in seq]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
728x90
728x90

'Programming > Python' 카테고리의 다른 글

Serialization, pickling - 직렬화  (0) 2020.10.07
lambda - 람다  (0) 2020.10.06
generator, iterator, yield  (0) 2020.09.30
False - 거짓  (0) 2020.09.28
input(), sys.stdin - 코딩테스트 시 입력받기  (0) 2020.09.24
Buy me a coffeeBuy me a coffee

댓글