수색…


통사론

  • map (함수, iterable [, * additional_iterables])
  • future_builtins.map (함수, iterable [, * additional_iterables])
  • itertools.imap (함수, iterable [, * additional_iterables])

매개 변수

매개 변수 세부
기능 매핑을위한 함수 (iterables만큼 많은 매개 변수를 취해야 함) ( 위치 한정 )
반복 가능한 함수는 iterable ( 위치 한정 )의 각 요소에 적용됩니다.
* additional_iterables iterable을 참조하십시오. 그러나 원하는만큼 지정할 수 있습니다 ( 선택 사항 , 위치 기반 전용 ).

비고

map 할 수있는 모든 것은 또한 comprehensions 할 수 있습니다 :

list(map(abs, [-1,-2,-3]))    # [1, 2, 3]
[abs(i) for i in [-1,-2,-3]]  # [1, 2, 3]

비록 당신은 여러개의 iterable을 가지고 있다면 zip 이 필요할 것이다.

import operator
alist = [1,2,3]
list(map(operator.add, alist, alist))  # [2, 4, 6]
[i + j for i, j in zip(alist, alist)]  # [2, 4, 6]

List comprehensions은 효율적이고 많은 경우에 map 보다 빠를 수 있으므로 속도가 중요 할 경우 두 접근법의 시간을 테스트하십시오.

map, itertools.imap 및 future_builtins.map의 기본 사용

map 함수는 함수형 프로그래밍에 사용되는 파이썬 내장 함수 중에서 가장 간단한 함수입니다. map() 은 반복 함수의 각 요소에 지정된 함수를 적용합니다.

names = ['Fred', 'Wilma', 'Barney']
Python 3.x 3.0
map(len, names)  # map in Python 3.x is a class; its instances are iterable
# Out: <map object at 0x00000198B32E2CF8>

future_builtins 모듈에는 Python 3 호환 map 이 포함되어 있습니다.

Python 2.x 2.6
from future_builtins import map  # contains a Python 3.x compatible map()
map(len, names)                  # see below
# Out: <itertools.imap instance at 0x3eb0a20>

또는 파이썬 2에서는 itertools imap 을 사용하여 생성기를 얻을 수 있습니다

파이썬 2.x 2.3
map(len, names)   # map() returns a list
# Out: [4, 5, 6]

from itertools import imap
imap(len, names)  # itertools.imap() returns a generator
# Out: <itertools.imap at 0x405ea20>

결과를 명시 적으로 list 으로 변환하여 Python 2와 Python 3의 차이점을 제거 할 수 있습니다.

list(map(len, names))
# Out: [4, 5, 6]

map() 은 상응하는 목록 이해 또는 생성자 표현식 으로 대체 될 수 있습니다.

[len(item) for item in names] # equivalent to Python 2.x map()
# Out: [4, 5, 6]

(len(item) for item in names) # equivalent to Python 3.x map()
# Out: <generator object <genexpr> at 0x00000195888D5FC0>

iterable의 각 값 매핑

예를 들어, 각 요소의 절대 값을 취할 수 있습니다.

list(map(abs, (1, -1, 2, -2, 3, -3))) # the call to `list` is unnecessary in 2.x
# Out: [1, 1, 2, 2, 3, 3]

익명 함수는 또한 목록 매핑을 지원합니다.

map(lambda x:x*2, [1, 2, 3, 4, 5])
# Out: [2, 4, 6, 8, 10]

십진수 값을 백분율로 변환 :

def to_percent(num):
    return num * 100

list(map(to_percent, [0.95, 0.75, 1.01, 0.1]))
# Out: [95.0, 75.0, 101.0, 10.0]

또는 달러를 유로화로 변환 (환율 있음) :

from functools import partial
from operator import mul

rate = 0.9  # fictitious exchange rate, 1 dollar = 0.9 euros
dollars = {'under_my_bed': 1000,
           'jeans': 45,
           'bank': 5000}

sum(map(partial(mul, rate), dollars.values()))
# Out: 5440.5

functools.partial 은 함수의 매개 변수를 수정하여 lambda 를 사용하거나 사용자 정의 함수를 만드는 대신 map 과 함께 사용할 수있는 편리한 방법입니다.

다른 iterables의 값 매핑

예를 들어 다중 iterables의 각 i 번째 요소의 평균을 계산하면 다음과 같습니다.

def average(*args):
    return float(sum(args)) / len(args)  # cast to float - only mandatory for python 2.x

measurement1 = [100, 111, 99, 97]
measurement2 = [102, 117, 91, 102]
measurement3 = [104, 102, 95, 101]

list(map(average, measurement1, measurement2, measurement3))
# Out: [102.0, 110.0, 95.0, 100.0]

파이썬의 버전에 따라 map 에 하나 이상의 iterable이 전달되면 다른 요구 사항이 있습니다 :

  • 함수는 iterable만큼 많은 매개 변수를 가져야합니다.

    def median_of_three(a, b, c):
        return sorted((a, b, c))[1]
    
    list(map(median_of_three, measurement1, measurement2))
    

    TypeError : median_of_three () missing 1 필수 위치 인수 : 'c'

    list(map(median_of_three, measurement1, measurement2, measurement3, measurement3))
    

    TypeError : median_of_three ()에는 3 개의 위치 인수가 있지만 4 개가 주어진다.

Python 2.x 2.0.1
  • map : 한 iterable이 여전히 완전히 소비되지 않는 한 매핑이 반복되지만 완전히 소비 된 iterables에서 None 으로 가정합니다.

    import operator
    
    measurement1 = [100, 111, 99, 97]
    measurement2 = [102, 117]
    
    # Calculate difference between elements
    list(map(operator.sub, measurement1, measurement2))
    

    TypeError : - : 'int'및 'NoneType'에 대해 지원되지 않는 피연산자 유형

  • itertools.imapfuture_builtins.map : 하나의 반복 가능 (iterable)이 중지되자 마자 매핑이 중지됩니다.

    import operator
    from itertools import imap
    
    measurement1 = [100, 111, 99, 97]
    measurement2 = [102, 117]
    
    # Calculate difference between elements
    list(imap(operator.sub, measurement1, measurement2))
    # Out: [-2, -6]
    list(imap(operator.sub, measurement2, measurement1))
    # Out: [2, 6]
    
Python 3.x 3.0.0
  • 하나의 반복 가능 (iterable)이 멈추자 마자 매핑이 멈 춥니 다.

    import operator
    
    measurement1 = [100, 111, 99, 97]
    measurement2 = [102, 117]
    
    # Calculate difference between elements
    list(map(operator.sub, measurement1, measurement2))
    # Out: [-2, -6]
    list(map(operator.sub, measurement2, measurement1))
    # Out: [2, 6]
    

지도로 조바꿈하기 : "None"을 함수 인자로 사용하기 (파이썬 2.x에만 해당)

from itertools import imap
from future_builtins import map as fmap # Different name to highlight differences

image = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]

list(map(None, *image))
# Out: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
list(fmap(None, *image))
# Out: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
list(imap(None, *image))
# Out: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

image2 = [[1, 2, 3],
          [4, 5],
          [7, 8, 9]]
list(map(None, *image2))
# Out: [(1, 4, 7), (2, 5, 8), (3, None, 9)]  # Fill missing values with None
list(fmap(None, *image2))
# Out: [(1, 4, 7), (2, 5, 8)]                # ignore columns with missing values
list(imap(None, *image2))
# Out: [(1, 4, 7), (2, 5, 8)]                # dito
Python 3.x 3.0.0
list(map(None, *image))

TypeError : 'NoneType'개체를 호출 할 수 없습니다.

그러나 비슷한 결과를 얻을 수있는 해결 방법이 있습니다.

def conv_to_list(*args):
    return list(args)

list(map(conv_to_list, *image))
# Out: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

직렬 및 병렬 매핑

map ()은 내장 함수이므로 'import'문을 사용할 필요없이 모든 곳에서 사용할 수 있습니다. print ()와 같이 모든 곳에서 사용할 수 있습니다. 예제 5를 보면 꽤 print (import pprint)를 사용하기 전에 import 문을 사용해야한다는 것을 알 수 있습니다. 따라서 pprint는 내장 함수가 아닙니다.

시리즈 매핑

이 경우 iterable의 각 인수는 오름차순으로 매핑 함수에 인수로 제공됩니다. 이것은 매핑 할 함수가 하나 뿐이므로 매핑 함수에 단일 인수가 필요한 경우에 발생합니다.

예제 1

insects = ['fly', 'ant', 'beetle', 'cankerworm']
f = lambda x: x + ' is an insect'
print(list(map(f, insects))) # the function defined by f is executed on each item of the iterable insects

~에 결과

['fly is an insect', 'ant is an insect', 'beetle is an insect', 'cankerworm is an insect']

예제 2

print(list(map(len, insects))) # the len function is executed each item in the insect list

~에 결과

[3, 3, 6, 10]

병렬 매핑

이 경우 매핑 함수의 각 인수는 모든 iterable (각 iterable에서 하나씩)에서 병렬로 가져옵니다. 따라서 제공되는 iterables의 수는 함수가 요구하는 인수의 수와 일치해야합니다.

carnivores = ['lion', 'tiger', 'leopard', 'arctic fox']
herbivores = ['african buffalo', 'moose', 'okapi', 'parakeet']
omnivores = ['chicken', 'dove', 'mouse', 'pig']

def animals(w, x, y, z):
    return '{0}, {1}, {2}, and {3} ARE ALL ANIMALS'.format(w.title(), x, y, z)

예제 3

# Too many arguments
# observe here that map is trying to pass one item each from each of the four iterables to len. This leads len to complain that
# it is being fed too many arguments
print(list(map(len, insects, carnivores, herbivores, omnivores)))

~에 결과

TypeError: len() takes exactly one argument (4 given)

예제 4

# Too few arguments
# observe here that map is suppose to execute animal on individual elements of insects one-by-one. But animals complain when
# it only gets one argument, whereas it was expecting four.
print(list(map(animals, insects)))

~에 결과

TypeError: animals() missing 3 required positional arguments: 'x', 'y', and 'z'

보기 5

# here map supplies w, x, y, z with one value from across the list
import pprint
pprint.pprint(list(map(animals, insects, carnivores, herbivores, omnivores)))

~에 결과

 ['Fly, lion, african buffalo, and chicken ARE ALL ANIMALS',
 'Ant, tiger, moose, and dove ARE ALL ANIMALS',
 'Beetle, leopard, okapi, and mouse ARE ALL ANIMALS',
 'Cankerworm, arctic fox, parakeet, and pig ARE ALL ANIMALS']


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow