Python
(파이썬) 내장함수 map()
코딩ABC
2024. 1. 2. 09:34
반응형
파이썬의 내장함수(Built-in Function)인 map() 함수에 대해 알아보겠습니다.
map(function, iterable, *iterables) |
iterable의 모든 항목에 function(함수)을 적용하여 결과를 산출하는 반복자를 반환합니다.
iterables 처럼 반복 가능한 여러 인수를 사용할 수 있으며, iterables의 항목에 병렬로 적용됩니다.
여러 iterable을 사용하면 가장 짧은 iterable이 소진되면 반복자가 중지됩니다.
예제 1
리스트의 각 단어의 길이를 계산합니다.
words = ['apple', 'banana', 'cherry']
word_lengths = list(map(len, words))
print(word_lengths)
(Output)
[5, 6, 6]
예제 2
각 요소에 2를 곱합니다.
my_tuple = (2, 4, 6, 8, 10)
doubled_elements = tuple(map(lambda x: x * 2, my_tuple))
print(doubled_elements)
(Output)
(4, 8, 12, 16, 20)
예제 3
정수 리스트를 문자열로 변환합니다.
numbers = [1, 2, 3, 4, 5]
str_numbers = list(map(str, numbers))
print(str_numbers)
(Output)
['1', '2', '3', '4', '5']
예제 4
리스트에서 짝수가 아닌 항목만 필터링합니다.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers)
(Output)
[1, 3, 5, 7, 9]
예제 5
이 예에서 add_two는 세 개의 인수를 가져와 그 합계를 반환하는 함수입니다.
# Define a function that takes three arguments and returns their sum
def add_three(x, y, z):
return x + y + z
# Create three lists of numbers
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
# Use map to apply the function to corresponding elements of the three lists
result = list(map(add_three, list1, list2, list3))
# Print the result
print(result)
(Output)
[12, 15, 18]
반응형