嵌套列表推导,其中内部循环范围依赖于外部循环

时间:2016-09-13 20:32:39

标签: python python-3.x list-comprehension nested-loops

我试图将以下内容表示为列表理解:

L = []
for x in range(n):
    for y in range(x):
        L.append( (x, y) )

我在更典型的矩阵场景中完成了嵌套列表理解,其中内部循环范围不依赖于外部循环。

我认为itertools中可能存在使用product()chain()的解决方案,但在那里也没有成功。

3 个答案:

答案 0 :(得分:3)

请记住将x, y括在括号中这是唯一的一个警告,如果省略则导致SyntaxError

除此之外,翻译非常简单;理解中for的顺序与嵌套语句的顺序类似:

n = 5
[(x, y) for x in range(n) for y in range(x)]

产生与其嵌套循环对应项类似的结果:

[(1, 0),
 (2, 0),
 (2, 1),
 (3, 0),
 (3, 1),
 (3, 2),
 (4, 0),
 (4, 1),
 (4, 2),
 (4, 3)]

答案 1 :(得分:0)

以下是将代码转换为列表理解的示例。

>>> n = 10
>>> [ (x,y) for x in range(n) for y in range(x)]
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8)]

或者,使用itertools库获得相同的结果(仅为了解您的知识信息而共享它,但不建议用于此问题声明):

>>> import itertools
>>> list(itertools.chain.from_iterable(([(list(itertools.product([x], range(x)))) for x in range(n)])))
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8)]

答案 2 :(得分:0)

列表推导旨在使该循环的直接翻译成为可能:

[ (x,y) for x in range(3) for y in range(x) ]

这不是你想要的吗?