【发布时间】:2014-04-01 05:34:52
【问题描述】:
我想编写一个functional 等价于仅使用高阶函数且没有副作用的列表推导式。我这样做是为了严格的学习目的。 我知道列表推导是 Pythonic。 在 Python 中,map(f, xs) 等价于 [f(x) for x in xs]。但是下面这些的等价物是什么?
- 答:
[f(x, y) for x in xs for y in ys] - 乙:
[f(x, y) for x in range(1, 5) for y in range(x, 5)]
map 只返回相同长度的列表。 reduce 比较通用,可以在上面实现map 和filter。
map(f, xs) == reduce(lambda a, e: a + [f(e)], xs, [])
filter(p, xs) == reduce(lambda a, e: a + [e] if p(e) else a, xs, [])
因此A可以实现为:
def map2(f, xs, ys):
reduce(lambda a, x: a + map(lambda y: f(x, y), ys), xs, [])
但这并不能概括为 >2 for 子句。而 B 则更加棘手,因为第一个 for 子句中的迭代变量用于第二个子句。如何编写实现列表理解功能的函数(或函数集)?
【问题讨论】:
标签: python map functional-programming list-comprehension fold