python中filter(),map()和reduce()的区

2019-01-14  本文已影响6人  SugeonYen

filter()  返回true的,插入list   

map() 返回结果插入list

和map及list联合使用

>>> import sys

>>> showall = lambda x:list(map(sys.stdout.write,x))

>>> showall(['Jerry\n','Sherry\n','Alice\n'])

Jerry

Sherry

Alice

>>> showall(['Jerry','Sherry','Alice'])

JerrySherryAlice

等价于下面

>>> showall = lambda x: [sys.stdout.write(line) for line in x]

>>> showall(('I\t','Love\t','You!'))

I Love You![None, None, None]

例06: 在Tkinter中定义内联的callback函数

import sys

from Tkinter import Button,mainloop

x = Button(text='Press me',

command=(lambda:sys.stdout.write('Hello,World\n')))

x.pack()

x.mainloop()

>>> 

Hello,World!

Hello,World!

例07: lambda和map联合使用,

>>>  out = lambda *x: sys.stdout.write(' '.join(map(str,x)))

>>> out('This','is','a','book!\n')

This is a book!

例08: 判断字符串是否以某个字母开头

>>> print (lambda x: x.startswith('B'))('Bob')

True

-----

>>> Names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']

>>> B_Name= filter(lambda x: x.startswith('B'),Names)

>>> B_Name

['Bob', 'Barbara']

例09: lambda和map联合使用:

>>>  squares = map(lambda x:x**2,range(5))

>>> squares

[0, 1, 4, 9, 16]

例10. lambda和map,filter联合使用:

>>>  squares = map(lambda x:x**2,range(10))

>>> filters = filter(lambda x:x>5 and x<50,squares)

>>> filters

[9, 16, 25, 36, 49]

例11. lambda和sorted联合使用

#按death名单里面,按年龄来排序

#匿名函数的值返回给key,进来排序

>>> death = [ ('James',32),

('Alies',20),

('Wendy',25)]

>>> sorted(death,key=lambda age:age[1]) #按照第二个元素,索引为1排序

[('Alies', 20), ('Wendy', 25), ('James', 32)]

例12. lambda和reduce联合使用

>>> L = [1,2,3,4]

>>> sum = reduce(lambda x,y:x+y,L)

>>> sum

10

例13. 求2-50之间的素数

#素数:只能被1或被自己整除的数

>>> nums = range(2,50)

>>> for i in nums:

nums = filter(lambda x:x==i or x % i,nums)

>>> nums

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

例14. 求两个列表元素的和

>>> a = [1,2,3,4]

>>> b = [5,6,7,8]

>>> map(lambda x,y:x+y, a,b)

[6, 8, 10, 12]

例15. 求字符串每个单词的长度 

>>> sentence = "Welcome To Beijing!"

>>> words = sentence.split()

>>> lengths = map(lambda x:len(x),words)

>>> lengths

[7, 2, 8]

写成一行:

>>>  print map(lambda x:len(x),'Welcome To Beijing!'.split())

部分参考玩蛇网:http://www.iplaypy.com/wenda/lambda.html

部分参考csdn:http://blog.csdn.net/csdnstudent/article/details/40112803

上一篇 下一篇

猜你喜欢

热点阅读