{%hackmd @88u1wNUtQpyVz9FsQYeBRg/r1vSYkogS %}
# python lambda, reduce map and filter
> Lee Tsung-Tang
###### tags: `python` `list` `lambda` `reduce` `filter`
[TOC]
<br/>
## ```lambda()```
很多時候需要一個輕量的自訂函數,但又不想要另外儲存時常常會使用```lambda```來處理。
例如:
```python=
max = lambda m, n: m if m > n else n
print(max(10, 3)) # 顯示 10
```
原本的形式為:
```python=
def max(m, n):
return m if m > n else n
print(max(10, 3)) # 顯示 10
```
在```lambda```的定義函數中,冒號前代表函數的argument,後面代表expression。
<br/>
filter, map, reduce 都是針對集合物件處理的特殊函式。
可有助於python的資料處理以及程式簡化。
## ```map()```
Format: map(function, sequence
iterate所有的sequence的元素並將傳入的function作用於元素,最後以List作為回傳值。
例子:
```python=
# Create a list of strings: spells
spells = ["protego", "accio", "expecto patronum", "legilimens"]
# Use map() to apply a lambda function over spells: shout_spells
shout_spells = map(lambda item : item+'!!!' , spells)
# Convert shout_spells to a list: shout_spells_list
shout_spells_list = list(shout_spells)
# Print the result
print(shout_spells_list)
```

## ```filter()```
Format: filter(function, sequence)
以傳入的boolean function作為條件函式,iterate所有的sequence的元素並收集 function(元素) 為True的元素到一個List。
```python=
fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf']
# Use filter() to apply a lambda function over fellowship: result
result = filter(lambda member : len(member) > 6 , fellowship)
# Convert result to a list: result_list
result_list = list(result)
# Print result_list
print(result_list)
```

### note::
很多時候我們是想從list內取出index,而非直接subset。
因為取出index後可以進一步對data frame做subset
1. 使用L.index(),缺點是只會找出第一個match element的index
```python=
["foo", "bar", ,"bar" "baz"].index("bar")
```

2. 使用for迴圈
```python=
[index for index, ele in enumerate([1, 2, 1]) if ele == 1]
```

[Data Structures > More on Lists](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists)
<br/>
## ```reduce()```
Format: reduce(function, sequence)
必須傳入一個binary function(具有兩個參數的函式),最後僅會回傳單一值。
reduce會依序先取出兩個元素,套入function作用後的回傳值再與List中的下一個元素一同作為參數,以此類推,直到List所有元素都被取完。
```python=
# Import reduce from functools
import functools
# Create a list of strings: stark
stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon']
# Use reduce() to apply a lambda function over stark: result
result = functools.reduce(lambda item1 ,item2 : item1 + item2, stark)
# Print the result
print(result)
>>> robbsansaaryabrandonrickon
```
下面的圖片輔助說明上面範例程式中的reduce()是如何作用的:
