當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python map()用法及代碼示例

map()函數在將給定函數應用於給定可迭代項的每個項目(列表,元組等)之後,返回結果的映射對象(它是迭代器)。

用法:

map(fun, iter)

參數:


  • fun:映射將給定可迭代的每個元素傳遞給它的函數。
    iter:這是一個要映射的可迭代對象。

注意:您可以將一個或多個可迭代傳遞給map()函數。

返回值:

Returns a list of the results after applying the given function  
to each item of a given iterable (list, tuple etc.) 


注意:然後,可以將map()(Map對象)的返回值傳遞給list()(創建列表),set()(創建集合)之類的函數。

代碼1

# Python program to demonstrate working 
# of map. 
  
# Return double of n 
def addition(n):
    return n + n 
  
# We double all numbers using map() 
numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result))

輸出:

{2, 4, 6, 8}


代碼2
我們還可以將lambda表達式與map一起使用以實現上述結果。

# Double all numbers using map and lambda 
  
numbers = (1, 2, 3, 4) 
result = map(lambda x:x + x, numbers) 
print(list(result))

輸出:

{2, 4, 6, 8}


代碼3

# Add two lists using map and lambda 
  
numbers1 = [1, 2, 3] 
numbers2 = [4, 5, 6] 
  
result = map(lambda x, y:x + y, numbers1, numbers2) 
print(list(result))

輸出:

[5, 7, 9]


代碼4

# List of strings 
l = ['sat', 'bat', 'cat', 'mat'] 
  
# map() can listify the list of strings individually 
test = list(map(list, l)) 
print(test)

輸出:

[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]


相關用法


注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 Python map() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。