python map()函数和lambda表达式
- 2018-02-01 13:43:00
- 六月
- 来源:
- http://blog.csdn.net/u013944212/article/details/55095687
- 转贴 1008
python map(fun,[arg]+)函数最少有两个参数,第一参数为一个函数名,第二个参数是对应的这个函数的参数(一般为一个或多个list)。
>>>def fun(x):
...
return x+
1
... >>>list(map(fun,[
1,
2,
3]))
>>>[
2,
3,
4]
- 1
- 2
- 3
- 4
- 5
多参数例子:
>>>def fun(x,y,z):
...
return x*y*z
... >>>list(map(fun,[
1,
2,
3],[
1,
2,
3],[
1,
2,
3]))
>>>[
1,
8,
27]
- 1
- 2
- 3
- 4
- 5
(python 3.x 中map函数返回的是iterators,无法像python2.x 直接返回一个list,故需要再加上一个list()将iterators转化为一个list)。
lambda表达式:有人说类似于一种匿名函数,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用。
>>>s = [
1,
2,
3]
>>>
list(
map(lambda x:x+
1,s))
>>>[
2,
3,
4]
- 1
- 2
- 3
这里的 lambda x:x+1 相当于 上面的fun()函数, lambda和(冒号): 之间相当于 fun()函数的参数, :(冒号)之后 x+1 相当于fun()函数的return x+1
>>>
s = [
1,
2,
3]
>>>list(
map(lambda
x,
y,z:
x
*y
*z ,
s,
s,
s))
>>>[
1,
8,
27]
- 1
- 2
- 3
如上。
发表评论