본문으로 바로가기

map(function, iterable)

https://docs.python.org/ko/3/library/functions.html#map

사용법은 다음과 같이 함수명, 반복가능한 iterable 객체를 받아서 각 요소를 함수에 적용합니다.

def func(x):
    return x + 10 

m = map(func, range(10))
print(m)
print(list(m))
더보기
<map object at 0x000001914A0CA788>
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

 

filter(function, iterable)

https://docs.python.org/ko/3/library/functions.html#filter

사용법은 map() 함수와 비슷하지만 filter() 는 함수의 결과, 참/거짓에 따라 요소를 필터링합니다.

그 특성에 따라 #2 와 같이 사용할 수 있습니다.

colors = ['red', 'green', 'blue', 'black']

#1
f1 = filter(lambda c: True if c != 'black' else False, colors)
#2
f2 = filter(lambda c: c != 'black', colors)

print(list(f1))
print(list(f2))
더보기
['red', 'green', 'blue']
['red', 'green', 'blue']

 

map() vs filter() vs comprehension express ?

filter() 함수는 다음과 같이 요소를 간편하게 필터링할 수 있습니다.

colors = ['red', 'green', 'blue', 'black']
f = filter(lambda c: c != 'black', colors)
print(list(f))
더보기
['red', 'green', 'blue']

 

map() 함수를 이용해봅니다.

람다 표현식에서는 if 단독으로 사용하면 다음과 같이 에러가 납니다.

>>> colors = ['red', 'green', 'blue', 'black']
>>> m = map(lambda c: c if c != 'black', colors)
  File "<stdin>", line 1
    m = map(lambda c: c if c != 'black', colors)
                                       ^
SyntaxError: invalid syntax

pass 키워드 같은 것도 먹히지 않습니다.

SyntaxError: invalid syntax
>>> m = map(lambda c: c if c != 'black' else pass, colors) 
  File "<stdin>", line 1
    m = map(lambda c: c if c != 'black' else pass, colors)
                                                ^
SyntaxError: invalid syntax

최선인 것 같습니다..

>>> m = map(lambda c: c if c != 'black' else None, colors)      
>>> list(m)
['red', 'green', 'blue', None]

 

다음은 컴프리헨션 표현식입니다.

가장 직관적이고 쉽게 사용할 수 있는 표현식 같습니다.

>>> c = [c for c in colors if c != 'black'] 
>>> c
['red', 'green', 'blue']