在 python 當中經常會操作列表這樣的可迭代對象,如果有多層嵌套列表,操作起來會非常麻煩,用 map 可以讓代碼可讀性增強。
什么是 map 函數
map 函數是 python 內置函數,可以根據對列表這樣的可迭代類型做進一步操作。在新的 python3 中,map 不再是一個函數,而是一個類,但是還是習慣被稱為內置函數,官網也沒有更正。所以之后我們還是稱為 map 函數。
map 函數有 2 個參數,參數 function 表示要對每一個元素進行的操作,參數 iterables 是一個可迭代對象。返回值是經過 function 操作后的新對象, 在 python3 中是一個 map 對象。
(map 函數解釋圖)
看一個例子:在這個例子中,我們需要對 origin_iterable 這個列表中的每一個元素求絕對值,得到新數據。由於 map 返回值是一個 map 對象,需要轉化成 list 才能得到 [1, 3, 5]
origin_iterable = [1, -3, -5]
new_iterable = map(abs, origin_iterable)
print(new_iterable)
# <map object at 0x0000020E21D3E910>
print(list(new_iterable)
# [1, 3, 5]
除了列表,map 也可以操作元組:
origin_iterable = (1, -3, -5)
new_iterable = map(abs, origin_iterable)
print(tuple(new_iterable))
也可以操作 set 集合:
origin_iterable = {1, -3, -5}
new_iterable = map(abs, origin_iterable)
print(list(new_iterable))
可以操作字典,但是操作的是 key :
origin_iterable = {"name": "yuz", "age": 18}
new_iterable = map(str, origin_iterable)
print(list(new_iterable))
# ['name', 'age']
function 參數
map(function, *iterable) 第一個參數 function 是一個任意的函數。如果后面只有一個參數, function 函數接收一個參數。
如果后面有 2 個參數, function 函數則需要接收 2 個參數, 參數是 iterable 當中的元素。
def add(x, y):
return x + y
def demo_05():
origin_iterable_1 = [5, -2, 4]
origin_iterable_2 = [1, 8, 6]
new_iterable = map(add, origin_iterable_1, origin_iterable_2)
print(list(new_iterable))
對多個數據進行格式轉化
現在有一個二維數據需要處理,比如 Excel 中的數據,或者數據庫當中的數據。每個數據都是一個對象 Cell, 我想取出其中的值。
```python
class Cell:
def init(self, value):
self.value = value
def demo_06():
rows = [
(Cell(1), Cell(2), Cell(3)),
(Cell(7), Cell(8), Cell(9))
]
new_data = []
for row in rows:
new_row = tuple(map(lambda x: x.value, row))
new_data.append(new_row)
return new_data