Python map()函數
map()
是Python中的內置函數,它將函數應用於給定可迭代對象中的所有元素。 它允許您編寫簡單幹凈的代碼,而無需使用循環。
蟒蛇 map()
功能編號
的 map()
函數採用以下形式:
map(function, iterable, ...)
它接受兩個強制性參數:
function
-為每個元素調用的函數iterable
。iterable
-一個或多個支持迭代的對象。 Python中的大多數內置對象(如列表,字典和元組)都是可迭代的。
在Python 3中, map()
返回大小等於傳遞的可迭代對象的地圖對象。 在python 2中,該函數返回一個列表。
讓我們看一個例子,以更好地解釋 map()
功能起作用。 假設我們有一個字符串列表,我們希望將列表中的每個元素都轉換為大寫。
一種方法是使用傳統的 for
循環:
directions = ["north", "east", "south", "west"]
directions_upper = []
for direction in directions:
d = direction.upper()
directions_upper.append(d)
print(directions_upper)
['NORTH', 'EAST', 'SOUTH', 'WEST']
用 map()
功能,代碼將更加簡單和靈活。
def to_upper_case(s):
return s.upper()
directions = ["north", "east", "south", "west"]
directions_upper = map(to_upper_case, directions)
print(list(directions_upper))
我們正在使用 list()
將返回的地圖對象轉換為列表的構造函數:
['NORTH', 'EAST', 'SOUTH', 'WEST']
如果回調函數很簡單,那麼更多的Python方式是使用lambda函數:
directions = ["north", "east", "south", "west"]
directions_upper = map(lambda s: s.upper(), directions)
print(list(directions_upper))
Lambda函數是一個小的匿名函數。
這是另一個示例,顯示了如何創建從1到10的平方數列表:
squares = map(lambda n: n*n , range(1, 11))
print(list(squares))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
的 range()
函數生成整數序列。
使用 map()
有多個Iterables
您可以根據需要將任意數量的可迭代對象傳遞給 map()
功能。 回調函數接受的必需輸入參數的數量必須與可迭代的數量相同。
下面的示例顯示如何在兩個列表上執行逐元素乘法:
def multiply(x, y):
return x * y
a = [1, 4, 6]
b = [2, 3, 5]
result = map(multiply, a, b)
print(list(result))
[2, 12, 30]
相同的代碼,但使用lambda函數的外觀如下:
a = [1, 4, 6]
b = [2, 3, 5]
result = map(lambda x, y: x*y, a, b)
print(list(result))
當提供多個可迭代時,返回的對象的大小等於最短的可迭代。
讓我們看一個可迭代對象的長度不相同的示例:
a = [1, 4, 6]
b = [2, 3, 5, 7, 8]
result = map(lambda x, y: x*y, a, b)
print(list(result))
多餘的元素(7和8)將被忽略:
[2, 12, 30]
結論#
Python的 map()
函數接受一個可迭代對象以及一個函數,並將該函數應用於可迭代對象中的每個元素。
如果您有任何疑問或反饋,請隨時發表評論。
蟒蛇