python高級特性
1、集合的推導式
- 列表推導式,使用一句表達式構造一個新列表,可包含過濾、轉換等操作。
語法:[exp for item in collection if codition]
if codition - 可選



- 字典推導式,使用一句表達式構造一個新列表,可包含過濾、轉換等操作。
語法:{key_exp:value_exp for item in collection if codition}

- 集合推導式
語法:{exp for item in collection if codition}

- 嵌套列表推導式

2、多函數模式
函數列表,python中一切皆對象。
# 處理字符串
str_lst = ['$1.123', ' $1123.454', '$899.12312']
def remove_space(str):
"""
remove space
"""
str_no_space = str.replace(' ', '')
return str_no_space
def remove_dollar(str):
"""
remove $
"""
if '$' in str:
return str.replace('$', '')
else:
return str
def clean_str_lst(str_lst, operations):
"""
clean string list
"""
result = []
for item in str_lst:
for op in operations:
item = op(item)
result.append(item)
return result
clean_operations = [remove_space, remove_dollar]
result = clean_str_lst(str_lst, clean_operations)
print result
執行結果:['1.123', '1123.454', '899.12312']
3、匿名函數lambda
- 沒有函數名
- 單條語句組成
- 語句執行的結果就是返回值
- 可用作sort的key函數

python高階函數
1、函數式編程
- 函數本身可以賦值給變量,賦值后變量為函數;
- 允許將函數本身作為參數傳入另一個函數;
- 允許返回一個函數。


2、map/reduce函數
- map(fun, lst),將傳入的函數變量func作用到lst變量的每個元素中,並將結果組成新的列表返回


- reduce(func(x,y),lst),其中func必須有兩個參數。每次func計算的結果繼續和序列的下一個元素做累積計算。
lst = [a1, a2 ,a3, ......, an]
reduce(func(x,y), lst) = func(func(func(a1, a2), a3), ......, an)

3、filter函數
- 篩選序列
- filter(func, lst),將func作用於lst的每個元素,然后根據返回值是True或False判斷是保留還是丟棄該元素。

