标签:
python 中内置的几个函数filter, map, reduce, lambda简单的例子。
#!/usr/bin/env python #_*_coding:utf-8_*_ #filter(function, sequence): #对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回。 #可以看作是过滤函数。 tasks = [ { ‘id‘: 1, ‘title‘: u‘golang‘, ‘description‘: u‘Golang‘, ‘done‘: False }, { ‘id‘: 2, ‘title‘: u‘Learn Python‘, ‘description‘: u‘Need to find a good Python tutorial on the web‘, ‘done‘: False } ] def get_task(task_id): task = filter(lambda t: t[‘id‘] == task_id, tasks) print task get_task(2) # map(function, sequence) # 对sequence中的item依次执行function(item),执行结果组成一个List返回 def add(x, y): return x + y print map(add, range(10), range(10)) print map(lambda x,y:x+y, range(10), range(10)) def _str(s): s = s + ".log" return s s = ["a", "b", "c"] print map(_str, s) #reduce(function, sequence, starting_value) #对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和 print reduce(add, range(1, 10))
结果为:
[{‘description‘: u‘Need to find a good Python tutorial on the web‘, ‘done‘: False, ‘id‘: 2, ‘title‘: u‘Learn Python‘}] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] [‘a.log‘, ‘b.log‘, ‘c.log‘] 45
python中filter, map, reduce, lambda
标签:
原文地址:http://www.cnblogs.com/xurui/p/filter_map_reduce_lambda_function_in_python.html