Python的map、reduce和filter以及list comprehension(列表推导),,[Python]代码>>


[Python]代码

>>> 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]

评论关闭