1

Python支持运行时使用“lambda”建立匿名函数(anonymous functions that are not bound to a name)。

python "lambda"和functional programming语言有区别,但是他非常强大经常拿来和诸如filter(),map(),reduce()
等经典概念结合。

以下示例普通函数和匿名函数:

 In [113]: def normalFun (x): return x**2

 In [114]: print normalFun(8)
64 In [115]: anonymousFun = lambda x:x**2 In [116]: print anonymousFun(8)
64

普通函数和匿名函数运算结果都一样,但是匿名函数没有return语句,冒号后边

表达式就是返回值。

2 下面代码片段展示匿名函数用法,请保证python版本在2.2以上,因为需要支持嵌入作用域。

In [120]: def make_incrementor (n): return lambda x: x + n

In [121]: f = make_incrementor(2)

In [122]: g = make_incrementor(6)

In [123]: f
Out[123]: <function __main__.<lambda>> In [124]: g
Out[124]: <function __main__.<lambda>> In [125]: print(42)
42 In [126]: print f(42)
44 In [127]: print g(42)
48

注意,g,f 定义后类型显示位<function __main__.<lambda>>,说明此时g,f是匿名函数。

3 以下几个代码示范lambda和其他结合用法

In [133]: foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]

In [134]: print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27] In [135]: ?filter
Type: builtin_function_or_method
String form: <built-in function filter>
Namespace: Python builtin
Docstring:
filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list. In [136]: print filter(foo)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-136-a3d764429161> in <module>()
----> 1 print filter(foo) TypeError: filter expected 2 arguments, got 1 In [137]: print filter(None,foo)
[2, 18, 9, 22, 17, 24, 8, 12, 27]
          ?map
Type: builtin_function_or_method
String form: <built-in function map>
Namespace: Python builtin
Docstring:
map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence). In [140]: print map(lambda x: x* 2 + 100, foo)
[104, 136, 118, 144, 134, 148, 116, 124, 154] In [141]: foo
Out[141]: [2, 18, 9, 22, 17, 24, 8, 12, 27] In [142]:
In [146]: print reduce(lambda x,y: x + y, foo)
139 In [147]: ?reduce
Type: builtin_function_or_method
String form: <built-in function reduce>
Namespace: Python builtin
Docstring:
reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty. In [148]: foo
Out[148]: [2, 18, 9, 22, 17, 24, 8, 12, 27]

4 扩展:一些应用

4.1 The seive of Eratosthenes是埃及数学家Eratosthenes提出一种简单检定素数的算法,要得到自然数n以内全部素数,必须将不大于根号n的所有素数倍数剔除,剩下就是素数。

python实现如下:

#!/usr/bin/env python
from math import floor, sqrt
N = 50
n = int(sqrt(N))
nums = range(2, N)
for i in range(2, n):
nums = filter(lambda x: x==i or x % i, nums) print nums

4.2 字符串单词长度统计

#!/usr/bin/env python
sentence = 'It is raining cats and dogs'
words = sentence.split()
print words
lengths = map(lambda word: len(word), words)
print lengths

4.3 显示mount -v命令中所有挂载点

In [162]: ?commands.getoutput
Type: function
String form: <function getoutput at 0x7f348c60c9b0>
File: /usr/lib64/python2.7/commands.py
Definition: commands.getoutput(cmd)
Docstring: Return output (stdout or stderr) of executing cmd in a shell. In [163]: line = "gaga haha jiji" In [164]: ?line.split()
Type: builtin_function_or_method
String form: <built-in method split of str object at 0x7f348c660068>
Docstring:
S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.

代码:

#!/usr/bin/env python
import commands
mount = commands.getoutput('mount -v')
lines = mount.splitlines()
points = map(lambda line: line.split()[2], lines)
print points

python学习之lambda匿名函数的更多相关文章

  1. Python 进阶 之 lambda 匿名函数

    lambda 是个匿名函数,通常用于简单判断或者处理,例如判断一个数的奇偶性,过滤字符串,逻辑运算等等. lambda表达式: >>>lambda x:x*x >>> ...

  2. Python学习笔记010——匿名函数lambda

    1 语法 my_lambda = lambda arg1, arg2 : arg1 + arg2 + 1 arg1.arg2:参数 arg1 + arg2 + 1 :表达式 2 描述 匿名函数不需要r ...

  3. 记录我的 python 学习历程-Day13 匿名函数、内置函数 II、闭包

    一.匿名函数 以后面试或者工作中经常用匿名函数 lambda,也叫一句话函数. 课上练习: # 正常函数: def func(a, b): return a + b print(func(4, 6)) ...

  4. python 学习笔记2 匿名函数

    # 匿名函数 lambda a,b : a+b# a.j.from functools import reduce students = [{'name': '张三', 'age': 18, 'hei ...

  5. Python学习第九课——匿名函数

    匿名函数 # 匿名函数 func = lambda x: x + 1 # x表示参数 x+1表示处理逻辑 print(func(10)) # 输出结果为11 # 例:如何将name="han ...

  6. Python学习(五)函数 —— 内置函数 lambda filter map reduce

    Python 内置函数 lambda.filter.map.reduce Python 内置了一些比较特殊且实用的函数,使用这些能使你的代码简洁而易读. 下面对 Python 的 lambda.fil ...

  7. python基础-4 函数参数引用、lambda 匿名函数、内置函数、处理文件

    上节课总结 1.三元运算 name=“name1”if 条件 else “name2” 2.深浅拷贝 数字.字符串 深浅,都一样 2.其他 浅拷贝:只拷贝第一层 深拷贝:不拷贝最后一层 3.set集合 ...

  8. 『Python基础-14』匿名函数 `lambda`

    匿名函数和关键字lambda 匿名函数就是没有名称的函数,也就是不再使用def语句定义的函数 在Python中,如果要声匿名函数,则需要使用lambda关键字 使用lambda声明的匿名函数能接收任何 ...

  9. Python 之父为什么嫌弃 lambda 匿名函数?

    Python 支持 lambda 匿名函数,其扩展的 BNF 表示法是lambda_expr ::= "lambda" [parameter_list] ":" ...

随机推荐

  1. HDU 5893 List wants to travel(树链剖分)

    [题目链接]http://acm.hdu.edu.cn/showproblem.php?pid=5893 [题目大意] 给出一棵树,每条边上都有一个边权,现在有两个操作,操作一要求将x到y路径上所有边 ...

  2. NYOJ541 最强DE 战斗力(第五届省赛试题)

    最强DE 战斗力 时间限制:1000 ms  |  内存限制:65535 KB 难度: 描述 春秋战国时期,赵国地大物博,资源非常丰富,人民安居乐业.但许多国家对它虎视眈眈,准备联合起来对赵国发起一场 ...

  3. 如何用LinkedHashMap实现LRU缓存算法

    阿里巴巴笔试考到了LRU,一激动忘了怎么回事了..准备不充分啊.. 缓存这个东西就是为了提高运行速度的,由于缓存是在寸土寸金的内存里面,不是在硬盘里面,所以容量是很有限的.LRU这个算法就是把最近一次 ...

  4. 我的Hook学习笔记

    关于Hook 一.基本概念: 钩子(Hook),是Windows消息处理机制的一个平台,应用程序能够在上面设置子程以监视指定窗体的某种消息,并且所监视的窗体能够是其它进程所创建的.当消息到达后,在目标 ...

  5. android技术牛人的博客[转]

    Android+JNI调用–文件操作 开发环境:Windows xp sp3 +MyEclipse 8.6+android2.3.3+jdk1.6+android-ndk-r6b JNI概述:     ...

  6. iOS 10 因苹果健康导致闪退 crash

    如果在app中调用了苹果健康,iOS10中会出现闪退.控制台报出的原因是: Terminating app due to uncaught exception 'NSInvalidArgumentEx ...

  7. BZOJ 2326: [HNOI2011]数学作业( 矩阵快速幂 )

    BZOJ先剧透了是矩阵乘法...这道题显然可以f(x) = f(x-1)*10t+x ,其中t表示x有多少位. 这个递推式可以变成这样的矩阵...(不会用公式编辑器...), 我们把位数相同的一起处理 ...

  8. dubbo架构演变之路

    背景 (#) 随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,亟需一个治理系统确保架构有条不紊的演进. 单一应用架构 当网站流量很小时, ...

  9. HDU2007-平方和与立方和

    描述: 给定一段连续的整数,求出他们中所有偶数的平方和以及所有奇数的立方和. 代码: #include<stdio.h> #include<string.h> #include ...

  10. LintCode-两数之和

    题目描述: 给一个整数数组,找到两个数使得他们的和等于一个给定的数target. 你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标.注意这里下标的范围是1到n,不是以 ...