Python的map、reduce和filter以及list comprehension
216 views
0
>>> 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 # 上面的map和filter都可以用列表推导改写 print(filter(lambda x: x % 3 == 0, foo)) 等价于 print([x for x in foo if x % 3 == 0]) print(map(lambda x: x * 2 + 10, foo)) 等价于 print([x * 2 + 10 for x in foo]) # 求2到49范围内的素数 >>> nums = range(2, 50) >>> for i in range(2, 8): nums = [x for x in nums if x==i or x % i != 0] >>> nums [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2014-10-11 23:11:36
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!