python的lambda用法_python lambda的用法

Python通过构建"lambda"提供一种在程序运行时创建一个匿名函数的机制,即,函数不是和一个函数名绑定的。Python中的lambda并不函数式编程中的lambda,但是却是一个很强大的用法,通常和``map(), filter(), reduce()``联合起来使用。

- 和普通函数的区别

```

>>> def f(x) : return x**2

...

>>> print f(8)

64

>>> g = lambda x: x**2

>>>

>>> print g(8)

64

```

- 注意到,lambda并未包含一个return的声明,同样,在任何一个需要函数的地方都可以使用lambda而不需要指代一个函数名。

-----------------------

##进阶用法

```

>>> foo = [2,18,9,22,17,24,8,12,27]

>>> print filter(lambda x: x%3 == 0, foo)

[18, 9, 24, 12, 27]

>>>

>>> print map(lambda x: x*2+10, foo)

[14, 46, 28, 54, 44, 58, 26, 34, 64]

>>>

>>> print reduce(lambda x, y: x+y, foo)

139

```

P.S.

- map()用法

- map(function_to_apply, list_to_input)

- Most of the times we want to pass all the list elements to a function one-by-one and then collect the output.

- For Example

```

items = [1, 2, 3, 4, 5]

squared = []

for i in items:

squared.append(i**2)

```

这段的代码功能和下面的功能一样:

```

items = [1,2,3,4,5]

squared = list(map(lambda x: x**2, items))

```

- filter()用法

- filter creates a list of elements for which a function returns true.

- Reduce()用法

- reduce is a really usedful function for performing some computation on al list returning the result.

- It applies a rolling computation to sequential pairs of value.

- 下面的两个代码片段执行的功能是相等的:

```

product = 1

list = [1, 2, 3, 4]

for num in list:

product = product * num

# product = 24

```

```

from functools import reduce

product = reduce((lambda x, y: x * y), [1, 2, 3, 4])

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值