Home  >  Article  >  Backend Development  >  Python lambda和Python def区别分析

Python lambda和Python def区别分析

WBOY
WBOYOriginal
2016-06-10 15:18:391112browse

Python支持一种有趣的语法,它允许你快速定义单行的最小函数。这些叫做lambda的函数,是从Lisp借用来的,可以用在任何需要函数的地方。

lambda的语法时常会使人感到困惑,lambda是什么,为什么要使用lambda,是不是必须使用lambda?

>>> def f(x):
...   return x+2
...
>>> f(1)
3
>>> f = lambda x:x+2
>>> f(1)
3
>>> (lambda x:x+2)(1)
3

Python def和Python lambda它们有相似点也有不同点。
相似点: 这两个很重要的相似点就是都可以定义一些固定的方法或者是流程,供给程序来调用,比如上面例子中定义一个变量加2的方法。 输出的结果都是3,如果你要完成一些固定的流程的话,上面几种你都可以任意选择。

上面是相同点,那么有那些不同点?
它们的主要不同点是Python def是语句而Python lambda是表达式。lambda简化了函数定义的书写形式,使代码更为简洁。但是使用函数的定义方式更为直观,易理解。

Python里面语句是可以嵌套的,比如你需要根据某个条件来定义方法,那只能用def。用lambda就会报错。

>>> if a==1:
...   def info():
...     print '1'*5
... else:
...   def info2():
...     print 'info2'

而有的时候你需要在python表达式里操作的时候,那需要用到表达式嵌套,这个时候Python def就不能得到你想要的结果,那只能用Python lambda,如下例子:
输出e字符串出现频率最高的字母:

>>> str='www.linuxeye.com linuxeye.com'
>>> L = ([(i,str.count(i)) for i in set(str)])
[(' ', 1), ('c', 2), ('e', 4), ('i', 2), ('m', 2), ('l', 2), ('o', 2), ('n', 2), ('u', 2), ('w', 3), ('y', 2), ('x', 2), ('.', 3)]
>>> L.sort(key = lambda k:k[1],reverse = True)
>>> print L[0][0]
e
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn