前言
剛開(kāi)始接觸python的函數(shù),有沒(méi)有很難理解,為什么要這樣做我這樣不行嗎?試了N多次還是以一段錯(cuò)誤提示反饋給你,最后還是選擇百度搜索一下這個(gè)函數(shù)到底怎么使用。其實(shí)看官方的文檔也是能找到答案的。
map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended withNoneitems. If function isNone, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.
Wow,全是英文剛開(kāi)始看是會(huì)覺(jué)的一個(gè)頭兩個(gè)大,不懂就拿手機(jī)查,多次之后,你會(huì)覺(jué)得我也是能看懂英文的人啦。一起來(lái)看一下這個(gè)函數(shù)是怎么使用的。
map函數(shù)定義:
它接收一個(gè)函數(shù) f 和一個(gè) list,并通過(guò)把函數(shù) f 依次作用在 list 的每個(gè)元素上,得到一個(gè)新的 list 并返回
因?yàn)閜ython3map函數(shù)返回的是迭代器,所以要轉(zhuǎn)成list才能打印
如果給出了額外的可迭代參數(shù),則對(duì)每個(gè)可迭代參數(shù)中的元素同時(shí)應(yīng)用‘function’。
map的另類用法:
map可以用列表解析代替
map(f, iterable)? 等價(jià)于? [f(x) for x in iterable]我們驗(yàn)證一下:
看一下結(jié)果:
貌似結(jié)果是一樣的相同,我們?cè)衮?yàn)證一下
結(jié)果好像不一樣了,列表解析好像是把結(jié)果全打印出來(lái)了,看來(lái)還是不能全部代替,如果能全部代替,那可能看不到map了。
map函數(shù)的應(yīng)用:
假設(shè)用戶輸入的英文名字不規(guī)范,沒(méi)有按照首字母大寫(xiě),后續(xù)字母小寫(xiě)的規(guī)則,請(qǐng)利用map()函數(shù),把一個(gè)list(包含若干不規(guī)范的英文名字)變成一個(gè)包含規(guī)范英文名字的list:
輸入:['adam', 'LISA', 'barT']
輸出:['Adam', 'Lisa', 'Bart']
結(jié)果如下: