為什么大神能輕松使用函數(shù):python之map函數(shù)!

前言

剛開(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é)果如下:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 函數(shù)調(diào)用 Built-in Functions abs(x) Return the absolute value ...
    叫我七夜閱讀 1,322評(píng)論 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評(píng)論 0 10
  • PYTHON-進(jìn)階-ITERTOOLS模塊小結(jié)轉(zhuǎn)自wklken:http://wklken.me/posts/20...
    C_Y_閱讀 1,183評(píng)論 0 2
  • 包(lib)、模塊(module) 在Python中,存在包和模塊兩個(gè)常見(jiàn)概念。 模塊:編寫(xiě)Python代碼的py...
    清清子衿木子水心閱讀 3,922評(píng)論 0 27
  • 【日精進(jìn)打卡648天】 姓名:玉生 沈陽(yáng)盛和商學(xué)院 六項(xiàng)精進(jìn)第177期學(xué)員(隊(duì)長(zhǎng)),271期284期288期295...
    _玉_生_閱讀 345評(píng)論 0 1

友情鏈接更多精彩內(nèi)容