将嵌套的 for 循环转换为等效的映射

Convert a nested for loop to a map equivalent

示例:

for x in iterable1:
    expression

map 形式为:

map(lambda x: expression, iterable1)

如何仅使用 map 且不使用列表理解将其扩展到嵌套 for 循环?

示例:

for x in itr1:
    for y in itr2:
        expr

你不能。 lambda 特别限于其 return 值可以封装为单个表达式的函数:不允许语句。

您应该问自己的一个问题是,为什么您认为这是编写 Python 程序的理想方式?该语言已明确定义为可读性,您应该尽一切努力保持可读性。

您可以使用 itertools.product 构建两个嵌套序列的笛卡尔积,并且 map 您的表达式到该 2 元组列表:

from itertools import product

map(lambda (x, y): expression, product(itr1, itr2))

具有一些实际值的示例:

seq = map(lambda (x, y): '%s:%s' % (x, y), product(itr1, itr2))
for item in seq:
    print item

请注意,lambda (x, y) 是将序列中的每个 2 元组解压缩为表达式中使用的单独 xy 参数所必需的。

请多多包涵。不是解释,但这在 2 天后起作用。仅使用地图和列表。这是糟糕的代码。欢迎提出缩短代码的建议。 Python3个解

使用列表理解的示例:

>>> a=[x+y for x in [0,1,2] for y in [100,200,300]]
>>> a
[100,200,300,101,201,301,102,202,302]

使用示例:

>>>a=[]
>>>for x in [0,1,2]:
...    for y in [100,200,300]:
...        a.append(x+y)
...
>>>a
[100,200,300,101,201,301,102,202,302]

现在仅使用地图的示例:

>>>n=[]
>>>list(map(lambda x:n.extend(map(x,[100,200,300])),map(lambda x:lambda y:x+y,[0,1,2])))
>>>n
[100,200,300,101,201,301,102,202,302]

小得多python2.7 解决方案:

>>>m=[]
>>>map(lambda x:m.extend(x),map(lambda x:map(x,[100,200,300]),map(lambda x:lambda y:x+y,[0,1,2])))
>>>m
[100,200,300,101,201,301,102,202,302]

另一种变体:我给 Mark Lutz 发了邮件,这是他的解决方案。这不使用闭包,并且最接近嵌套 for 循环功能。

>>> X = [0, 1, 2]               
>>> Y = [100, 200, 300]
>>> n = []
>>> t = list(map(lambda x: list(map(lambda y: n.append(x + y), Y)),X))
>>> n
[100,200,300,101,201,301,102,202,302]