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