您的位置:首页 > 编程语言 > Python开发

Python:函数式编程与函数

2016-04-05 14:31 495 查看

1. lambda 单行函数

lambda允许用户快速定义单行函数,目的是简化用户定义使用函数的过程。

func =lambda x: x *2   # 定义lambda函数,通过赋值给func进行调用

func(3)
>>> 6


lambda参数列表可以包含多个参数,如
lambda x, y: x + y


2. map(func,seq1[,seq2])

将func作用于seq中的每个元素,并用一个列表的形式给出返回值

3. 普通函数

3.1 函数的定义

def hello(name):
return 'hello ' + name + '!'

print hello('a')

>>>hello a!


递归函数举例:

def foo(i):
print 'the number is: ', i
i+=1
if i<10:
foo(i)
else:
print 'end!'

foo(0)


结果为:

>>>
the number is:  0
the number is:  1
the number is:  2
the number is:  3
the number is:  4
the number is:  5
the number is:  6
the number is:  7
the number is:  8
the number is:  9
end!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: