Python中的高阶函数map
生活随笔
收集整理的這篇文章主要介紹了
Python中的高阶函数map
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
map【映射】
1.map(fn,iter)
? ? ? ? ? ?fn:? 函數(shù)
? ? ? ? ? ? iter :? 序列【可迭代對(duì)象】
2.功能:
? ?會(huì)將iter中的每個(gè)元素用作于fn的運(yùn)算中,返回一個(gè)新的結(jié)果,產(chǎn)生一新的序列
3.生成一個(gè)序列,序列中的元素為1,4,9,16,25
# 方式一 def func1(x):return x ** 2result_1 = map(func1, range(1, 6)) print(result_1, type(result_1)) print(list(result_1))# 方式二 result_2 = map(lambda x: x ** 2, range(1, 6)) print(list(result_2)) # 也可以寫一塊 result_3 = list(map(lambda x: x ** 2, range(1, 6))) print(result_3)運(yùn)行結(jié)果:
"""注意:1.fn函數(shù)取決于iter的個(gè)數(shù)2.需要設(shè)置返回值,如果沒有返回值,最終生成的新的序列中的元素默認(rèn)為None """4.在map中可以使用多個(gè)序列
# 方式一 def add(x, y):return x + yresult_4 = map(add, [1, 2, 3], [4, 5, 6]) print(list(result_4))# 方式二 result_5 = map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]) print(list(result_5))打印結(jié)果:? ?[5, 7, 9]
5.將列表中每個(gè)整型元素轉(zhuǎn)換為字符串類型
list_1 = [1, 2, 3, 4, 5] print("轉(zhuǎn)換前:", list_1) result_6 = map(str, list_1) print("轉(zhuǎn)換后:", list(result_6))打印結(jié)果:
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Python中的高阶函数map的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 8.Java有关变量的面试题
- 下一篇: Python中的高阶函数reduce