ㅍㅍㅋㄷ

python map() 함수 본문

Programming/Python

python map() 함수

클쏭 2016. 7. 18. 15:39

python map() 함수


  python docs 의 map 함수에 대한 정의를 보자.


map(function, iterable, ...)


  Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.



 map() 함수는 built-in 함수로 list 나 dictionary 와 같은 iterable 한 데이터를 인자로 받아 list 안의 개별 item을 함수의 인자로 전달하여 결과를 list로 형태로 반환해 주는 함수이다. 글로 설명하면 복잡하니 아래 예제를 보자. 


def func(x):

return x * 2


인자로 받은 정수를 두배로 곱하여 반환해 주는 매우 간단한 함수이다.

이 함수에 인자를 map() 함수를 이용해 전달해 보자.


>>> map( func, [1, 2, 3, 4] )

[2, 4, 6, 8]


 위와 같이 map() 함수는 for문과 같은 반복문을 사용하지 않아도 지정한 함수로 인자를 여러번 전달해 그 결과를 list 형태로 뽑아 주는 유용한 함수이다. 한줄로 처리되다 보니 매우 간결한 형태의 코딩이 가능하다는 것이 큰 장점이다.

 

 map() 함수의 경우 보통 위와 같이 인자를 list 형태로 전달하는게 일반적이지만 iterable 한 형태인 dictionary 같은 인자도 가능하다. 


>>> x = { 1 : 10, 2 : 20, 3: 30 }

>>> map(func, x)

[ 2, 4, 6 ]


 dictionary 의 key 값이 전달되게 되지만, 아래와 같이 조금만 응용하면 value 값을 전달하는 것도 가능하다.


>>> x = { 1 : 10, 2 : 20, 3: 30 }

>>> map(func, [ x[i] for i in x ])


[ 20, 40, 60 ]



[ 참고 ]

  • https://docs.python.org/2/library/functions.html#map


Comments