python中map函数运行原理_Python中map函数的解释和可视化
先重溫一下迭代(Iteration)、迭代器對象(iterable)、迭代器(iterator )的概念:
Iteration是計(jì)算機(jī)科學(xué)的通用術(shù)語,它是指對一組元素執(zhí)行一項(xiàng)操作,一次執(zhí)行一個(gè)元素。一個(gè)很好的例子是循環(huán) - 它適用于每個(gè)單獨(dú)的項(xiàng)目,直到整個(gè)項(xiàng)目集運(yùn)行完畢為止。
Iterable是可以遍歷的對象(譯者注:在Python中所有東西都是object, 比如說變量,容器,類),iterable是可以產(chǎn)生iterator的object。
iterator是表示數(shù)據(jù)流的對象,它一次返回一個(gè)元素的數(shù)據(jù)。它還會(huì)記住其在迭代過程中的位置。本質(zhì)上,它控制應(yīng)如何迭代可迭代對象。
map()的用法
map()函數(shù)以迭代的方式將提供的功能應(yīng)用于每個(gè)項(xiàng)目,結(jié)果是作為迭代器的map對象。語法:
map(func, *iterables)
如果沒有map(),我們將不得不編寫復(fù)雜的代碼以在多個(gè)項(xiàng)目上“循環(huán)”給定的函數(shù)。以一個(gè)整潔的小實(shí)驗(yàn)為例:我們有一個(gè)10個(gè)單詞的列表。
test_list = ["effort", "circle", "yearly", "woolen", "accept", "lurker",
"island", "faucet", "glossy", "evader"]
我們懷疑其中一些可能是abcderian(按字母順序出現(xiàn)的)。我們編寫一個(gè)函數(shù)is_abecedarian來檢查給定的單詞是否為abcderian:
def is_abecedarian(input_word):
index = 0
for letter in input_word[0:-1]:
if ord(input_word[index]) > ord(input_word[index + 1]):
return False
else:
index += 1
return True
現(xiàn)在,我們想將函數(shù)應(yīng)用于單詞列表,并創(chuàng)建一個(gè)將包含True和False值的新列表,以表明某些單詞是否確實(shí)是abcderian。
下面方法涉及初始化一個(gè)新列表,然后使用for循環(huán)遍歷列表元素:
value_list = []
for item in test_list:
value = is_abecedarian(item)
value_list.append(value)
輸出:
[True, False, False, False, True, False, False, False, True, False]
如果用map(),我們可以將上面的代碼簡化為一個(gè)簡潔的小代碼:
map(is_abecedarian, test_list)
請注意map()不會(huì)返回列表,而是返回一個(gè)map對象。
譯者注:map()函數(shù)在python2中返回的是列表。
你可能很好奇哪個(gè)詞實(shí)際上是abcderian的字母-讓我們編寫這個(gè)問題的答案:
for item in test_list:
if is_abecedarian(item):
print(f"The word '{item}' is abecedarian. :)")
else:
print(f"The word '{item}' is not abecedarian. (")
輸出:
The word 'effort' is abecedarian. :)
The word 'circle' is not abecedarian.
The word 'yearly' is not abecedarian.
The word 'woolen' is not abecedarian.
The word 'accept' is abecedarian. :)
The word 'lurker' is not abecedarian.
The word 'island' is not abecedarian.
The word 'faucet' is not abecedarian.
The word 'glossy' is abecedarian. :)
The word 'evader' is not abecedarian.
我們還可以用可視化的方式形象地解釋,以幫助您更好地理解它:
這張圖也有助于定義 map 和mapping-我們可以使用Allen B. Downey在他的《Think Python》書中提供的定義:
映射操作(map):一種遍歷一個(gè)序列并對每個(gè)元素執(zhí)行操作的處理模式。
映射(mapping):一個(gè)集合中的每個(gè)元素對應(yīng)另一個(gè)集合中的一個(gè)元素的關(guān)系
將map()轉(zhuǎn)換為列表,元組和集合
由于map()不返回列表/元組/集合,因此我們需要采取額外的步驟來轉(zhuǎn)換生成的map對象:
def capitalize_word(input_word):
return input_word.capitalize()
map_object = map(capitalize_word, ['strength', 'agility', 'intelligence'])
test_list = list(map_object)
print(test_list)
map_object = map(capitalize_word, ['health', 'mana', 'gold'])
test_set = set(map_object)
print(test_set)
map_object = map(capitalize_word, ['armor', 'weapon', 'spell'])
test_tuple = tuple(map_object)
print(test_tuple)
輸出:
['Strength', 'Agility', 'Intelligence']
{'Mana', 'Health', 'Gold'}
('Armor', 'Weapon', 'Spell')
將map()與Lambda表達(dá)式結(jié)合
Lambda表達(dá)式是對我們的工具庫的一個(gè)很好的補(bǔ)充:將Lambda表達(dá)式與map()代碼相結(jié)合可使您的Python程序更小,更精確。
Lambda表達(dá)式可以創(chuàng)建匿名函數(shù),即未約定特定標(biāo)識(shí)符的函數(shù)。相反,通過def關(guān)鍵字創(chuàng)建函數(shù)會(huì)將函數(shù)綁定到其唯一標(biāo)識(shí)符(例如def my_function創(chuàng)建標(biāo)識(shí)符my_function)。
但是,lambda表達(dá)式也有一系列限制:它們每個(gè)只能做一件事情,只能在一個(gè)地方使用,通常與其他功能結(jié)合使用。我們看看lambda表達(dá)式如何map()同時(shí)使用:
cities = ["caracas", "bern", "oslo", "ottawa", "bangkok"]
def capitalize_word(input_word):
return input_word.capitalize()
capitalized_cities = map(capitalize_word, cities)
更簡潔的版本:
cities = ["caracas", "bern", "oslo", "ottawa", "bangkok"]
capitalized_cities = map(lambda s: s.capitalize(), cities)
需要注意:map()和lambda表達(dá)式提供了凝聚多行代碼成一行的能力。
盡管此功能非常出色,但我們需要牢記編程的黃金法則之一:代碼讀取比寫入更頻繁。這意味著map()和lambda表達(dá)式都可以提高代碼的簡潔性,但是卻犧牲了代碼的清晰度。遺憾的是,對于代碼的可讀性,實(shí)際上并沒有明確的指導(dǎo)方針- 隨著編程經(jīng)驗(yàn)的增長,大家將逐漸明白這一點(diǎn)。
使用map()遍歷字典
map()也非常適合遍歷字典
假設(shè)有一個(gè)包含蘋果,梨和櫻桃價(jià)格的字典,我們需要通過應(yīng)用15%的折扣來更新價(jià)格表。方法如下:
price_list = {
"pear": 0.60,
"cherries": 0.90,
"apple": 0.35,
}
def calulates_discount(item_price):
return (item_price[0], round(item_price[1] * 0.85, 2))
new_price_list = dict(map(calulates_discount, price_list.items()))
輸出:
{'pear': 0.51, 'cherries': 0.77, 'apple': 0.3}
將map()與Lambda表達(dá)式組合遍歷字典
當(dāng)開始組合多個(gè)功能時(shí),編程特別有趣,一個(gè)很好的例子是map()配合使用和lambda表達(dá)式來遍歷字典。在下面的代碼中,我們初始化字典列表,并將每個(gè)字典作為參數(shù)傳遞給lambda函數(shù)。
list_of_ds = [{'user': 'Jane', 'posts': 18}, {'user': 'Amina', 'posts': 64}]
map(lambda x: x['user'], list_of_ds) # Output: ['Jane', 'Amina']
map(lambda x: x['posts'] * 10, list_of_ds) # Output: [180, 640]
map(lambda x: x['user'] == "Jane", list_of_ds) # Output: [True, False]
map()替代方法:列表解析
像所有技術(shù)/產(chǎn)品/方法等等一樣,一些Python開發(fā)人員認(rèn)為map()函數(shù)在某種程度上不是Python風(fēng)格(即未遵循應(yīng)如何構(gòu)建Python程序的精神和設(shè)計(jì)理念)。他們建議改用列表解析,比如:
map(f, iterable)
變成
[f(x) for x in iterable]
在速度和性能方面,map()與列表理析大致相等,因此不可能看到執(zhí)行時(shí)間顯著減少 - 經(jīng)驗(yàn)豐富的Python開發(fā)者Wesley Chun在其演講Python 103:Memory Model&Best Practices中解決了這個(gè)問題,有興趣的同學(xué)可移步:
https://conferences.oreilly.com/oscon/oscon2013/public/schedule/detail/29374
By Denis Kryukov
本文由博客一文多發(fā)平臺(tái) OpenWrite 發(fā)布!
總結(jié)
以上是生活随笔為你收集整理的python中map函数运行原理_Python中map函数的解释和可视化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python连接mysql数据库数据库_
- 下一篇: c语言 python rsa库_Pyth