python源碼解釋如下:
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.
簡單來說,
map()它接收一個函數 f 和一個 可迭代對象(這里理解成 list),並通過把函數 f 依次作用在 list 的每個元素上,得到一個新的 list 並返回。
例如,對於list [1, 2, 3, 4, 5, 6, 7, 8, 9] 如果希望把list的每個元素都作平方,就可以用map()函數: 因此,我們只需要傳入函數f(x)=x*x,就可以利用map()函數完成這個計算: def f(x): return x*x print(list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) 輸出結果: [1, 4, 9, 10, 25, 36, 49, 64, 81]
配合匿名函數使用:
data = list(range(10))
print(list(map(lambda x: x * x, data)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
注意:map()函數不改變原有的 list,而是返回一個新的 list。 利用map()函數,可以把一個 list 轉換為另一個 list,只需要傳入轉換函數。 由於list包含的元素可以是任何類型,因此,map() 不僅僅可以處理只包含數值的 list,事實上它可以處理包含任意類型的 list,只要傳入的函數f可以處理這種數據類型。
任務 假設用戶輸入的英文名字不規范,沒有按照首字母大寫,后續字母小寫的規則,請利用map()函數,把一個list(包含若干不規范的英文名字)變成一個包含規范英文名字的list:
def f(s): return s[0:1].upper() + s[1:].lower() list_ = ['lll', 'lKK', 'wXy'] a = map(f, list_) print(a) print(list(a))
運行結果:
<map object at 0x000001AD0A334908>
['Lll', 'Lkk', 'Wxy']