环境
$ python --version Python 3.7.0
map
列表数据转换
# -*- coding: utf-8 -*- lst = [1, 2, 3] # map lst1 = list(map(lambda x: x * 2, lst)) print(lst1) # [2, 4, 6] # 列表生成式 lst2 = [x * 2 for x in lst] print(lst2) # [2, 4, 6]
filter
过滤列表元素
# -*- coding: utf-8 -*- lst = [1, 2, 3, 4, 5, 6] # filter lst1 = list(filter(lambda x: x > 3, lst)) print(lst1) # [4, 5, 6] lst2 = [x for x in lst if x > 3] print(lst2) # [4, 5, 6]
reduce
数据聚合,例如:求和
# -*- coding: utf-8 -*- from functools import reduce lst = [1, 2, 3, 4, 5] # reduce total = reduce(lambda x, y: x + y, lst, 0) print(total) # 15
# -*- coding: utf-8 -*- lst = [1, 2, 3, 4, 5] total = 0 for x in lst: total += x print(total) # 15