码迷,mamicode.com
首页 > 编程语言 > 详细

python中filter, map, reduce, lambda

时间:2016-05-15 22:52:27      阅读:699      评论:0      收藏:0      [点我收藏+]

标签:

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: ugolang,
        description: uGolang, 
        done: False
    },
    {
        id: 2,
        title: uLearn Python,
        description: uNeed 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: uNeed to find a good Python tutorial on the web, done: False, id: 2, title: uLearn 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!