웹사이트 검색

파이썬 맵() 함수


Python map() 함수는 지정된 iterable 및 반환 맵 객체의 모든 요소에 함수를 적용하는 데 사용됩니다. 파이썬 맵 객체는 팩토리 함수를 사용하는 튜플 등입니다.

파이썬 맵() 함수

Python map() 함수 구문은 다음과 같습니다.

map(function, iterable, ...)

여러 반복 가능한 인수를 map() 함수에 전달할 수 있습니다. 이 경우 지정된 함수에 해당 인수가 있어야 합니다. 이 반복 가능한 요소에 함수가 병렬로 적용됩니다. 여러 iterable 인수를 사용하면 가장 짧은 iterable이 소진되면 맵 반복자가 중지됩니다.

파이썬 맵() 예제

map() 함수와 함께 사용할 함수를 작성해 봅시다.

def to_upper_case(s):
    return str(s).upper()

입력 개체의 대문자 문자열 표현을 반환하는 간단한 함수입니다. 또한 반복자 요소를 인쇄하는 유틸리티 함수를 정의하고 있습니다. 이 함수는 공백이 있는 반복자 요소를 인쇄하고 모든 코드 스니펫에서 재사용됩니다.

def print_iterator(it):
    for x in it:
        print(x, end=' ')
    print('')  # for new line

다양한 유형의 이터러블이 있는 map() 함수 예제를 살펴보겠습니다.

문자열이 있는 Python map()

# map() with string
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)

산출:

<class 'map'>
A B C 

튜플이 있는 Python map()

# map() with tuple
map_iterator = map(to_upper_case, (1, 'a', 'abc'))
print_iterator(map_iterator)

산출:

1 A ABC 

목록이 있는 Python map()

map_iterator = map(to_upper_case, ['x', 'a', 'abc'])
print_iterator(map_iterator)

산출:

X A ABC 

맵을 리스트, 튜플, 세트로 변환

맵 객체는 이터레이터이기 때문에 리스트, 튜플, 세트 등을 생성하기 위한 팩토리 메소드의 인수로 전달할 수 있습니다.

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_list = list(map_iterator)
print(my_list)

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_set = set(map_iterator)
print(my_set)

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_tuple = tuple(map_iterator)
print(my_tuple)

산출:

['A', 'B', 'C']
{'C', 'B', 'A'}
('A', 'B', 'C')

람다를 사용한 Python map()

재사용하지 않으려면 map()과 함께 람다 함수를 사용할 수 있습니다. 이는 함수가 작고 새 함수를 정의하고 싶지 않을 때 유용합니다.

list_numbers = [1, 2, 3, 4]

map_iterator = map(lambda x: x * 2, list_numbers)
print_iterator(map_iterator)

산출:

2 4 6 8 

Python map() 다중 인수

반복 가능한 여러 인수와 함께 map() 함수를 사용하는 예를 살펴보겠습니다.

# map() with multiple iterable arguments
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)

출력: 5 12 21 32 함수에는 두 개의 인수가 있습니다. 출력 맵 반복자는 이 함수를 반복 가능한 두 요소에 병렬로 적용한 결과입니다. iterables의 크기가 다를 때 어떤 일이 발생하는지 봅시다.

# map() with multiple iterable arguments of different sizes
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8, 9, 10)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)

map_iterator = map(lambda x, y: x * y, tuple_numbers, list_numbers)
print_iterator(map_iterator)

산출:

5 12 21 32 
5 12 21 32 

따라서 인수의 크기가 다른 경우 요소 중 하나가 소진될 때까지 맵 함수가 요소에 적용됩니다.

None 함수를 사용하는 Python map()

함수를 None으로 전달할 때 어떤 일이 발생하는지 봅시다.

map_iterator = map(None, 'abc')
print(map_iterator)
for x in map_iterator:
    print(x)

산출:

Traceback (most recent call last):
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_map_example.py", line 3, in <module>
    for x in map_iterator:
TypeError: 'NoneType' object is not callable

GitHub 리포지토리에서 전체 Python 스크립트와 더 많은 Python 예제를 확인할 수 있습니다.

참조: 공식 문서