Language/Python

Python - map(), 함수와 iterable 변수를 인자로 받아 iterator 결과를 반환

TechNote.kr 2020. 2. 19. 23:21
728x90

map

 

>>> map(func, *iterables)

 

 

iterable 한 data를 func 의 인자로 넣어 나온 결과들을 iterator 형태로 반환해 주는 함수

 

[Link : iterable 과 iterator, 그리고 반복문]

 

map(functioniterable...)

Return an iterator that applies function to every item of iterable, yielding 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. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

 

[python3 기준]

>>> data = [1, 2, 3, 4, 5]
>>> def mul(item): 
...     return item * 4
... 
>>> map(mul, data)
<map object at 0x0000024658BC7448>
>>> list(map(mul, data))  
[4, 8, 12, 16, 20]

위와 같이 mul (function) 과 iterable 한 data (list) 를 map 의 인자로 전달하면 list의 각 element를 인자로 하여 mul 에 넣어 계산 후 결과들을 iterator 형태로 반환하게 된다.

 

iterator 를 list 형태로 변환 시키면 위와 같이 실제 값 확인이 가능하다. 

 

하지만 지능형 리스트의 소개 이후 map() 함수의 효용성은 떨어지고 있다. 

[Link : 지능형 리스트에 대한 이해]

 

다음과 같이 하면 지능형 리스트를 이용해 위의 map 예제를 동일하게 표현할 수 있다. 

>>> data = [1, 2, 3, 4, 5]
>>> def mul(item): 
...     return item * 4
... 
>>> [mul(n) for n in data]
[4, 8, 12, 16, 20]

 


>>> help(map)

Help on class map in module builtins:                                                                                                                                                                       

 

class map(object)

 |  map(func, *iterables) --> map object

 |  

 |  Make an iterator that computes the function using arguments from

 |  each of the iterables.  Stops when the shortest iterable is exhausted.

 |  

 |  Methods defined here:

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __iter__(self, /)

 |      Implement iter(self).

 |  

 |  __next__(self, /)

 |      Implement next(self).

 |  

 |  __reduce__(...)

 |      Return state information for pickling.

 |  

 |  ----------------------------------------------------------------------

 |  Static methods defined here:

 |

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 

 

 

728x90