http://blog.youkuaiyun.com/dysj4099/article/details/17412797
1. lambda 匿名函数
- >>> lambda_a = lambda a : a + 1
- >>> lambda_a(2)
- 3
构建一个函数lambda_a,不需要显示指定函数名,冒号之前是参数,此功能可以跟filter共同使用。 2. filter(func, seq) 用func过滤seq中的每个成员,并把func返回为True的成员构成一个新的seq
- >>> la = lambda a : a >= 10
-
- >>> test = [10, 1, 2, 15, 22, 13]
- >>> filter(la, test)
- [10, 15, 22, 13]
-
- >>> test2 = ['haha', 15, 10, 2]
- >>> filter(la, test2)
- ['haha', 15, 10]
-
- >>> la('test')
- True
- >>> la('best')
- True
- >>> la('%')
- True
-
- >>> test3 = [[], 15, 2]
- >>> filter(la, test3)
- [[], 15]
3. map(fun, seq) 用func处理seq中的每个成员,并组织成新seq返回
- >>> def a(x): return x**2
- ...
- >>> map(a, [1,2,3,4,5])
- [1, 4, 9, 16, 25]
4. reduce(func, seq, init_v) func必须为两个参数,对seq中的成员迭代调用func(return后的值参与下一次迭代),并且可以指定初始化值 init_v
- >>> def add(x, y): return x + y
- ...
- >>> reduce(add, range(1, 10), 15)
- 60
|
组合用法举例:
- >>> import string
- >>> str_path = ". : /usr/bin:/usr/local/bin/ : usr/sbin/ :"
- >>> filter(lambda path:path != '', map(lambda paths:string.strip(paths), string.split(str_path,':')))
- ['.', '/usr/bin', '/usr/local/bin/', 'usr/sbin/']
将字符串str_path 根据 ‘:’ 切分,过滤空字符串 并返回列表。 |