Skip to content

Instantly share code, notes, and snippets.

@lhsfcboy
Last active June 26, 2017 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lhsfcboy/1d7df14a3d1c3faca25e0c0e895e0f41 to your computer and use it in GitHub Desktop.
Save lhsfcboy/1d7df14a3d1c3faca25e0c0e895e0f41 to your computer and use it in GitHub Desktop.
Python中的函数编程
"""对于filter和map,在Python2中返回结果是列表,Python3中是生成器"""
import functools
map(lambda x: x**2, [1, 2, 3, 4]) # [1, 4, 9, 16]
map(lambda x, y: x + y, [1, 2, 3], [5, 6, 7]) # [6, 8, 10]
functools.reduce(lambda x, y: x + y, [1, 2, 3, 4]) # ((1+2)+3)+4=10
filter(lambda x: x % 2, [1, 2, 3, 4, 5]) # 筛选奇数,[1, 3, 5]
# map的两个例子和filter的一个例子可以用列表生成重写为:
[x**2 for x in [1, 2, 3, 4]] # [1, 4, 9 16]
[sum(x) for x in zip([1, 2, 3], [5, 6, 7])] # [6, 8, 10]
[x for x in [1, 2, 3, 4, 5] if x % 2] # [1, 3, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment