简体   繁体   English

嵌套列表理解,其中内部循环范围取决于外部循环

[英]Nested list comprehension where inner loop range is dependent on outer loop

I am trying to represent the following as a list comprehension: 我试图将以下内容表示为列表理解:

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

I have done nested list comprehension in the more typical matrix scenario where the inner loop range is not dependent on the outer loop. 我已经在更典型的矩阵方案中完成了嵌套列表理解,在这种方案中,内部循环范围不取决于外部循环。

I have considered there may be solutions in itertools , using product() or chain() but have been unsuccessful there as well. 我考虑过itertools可能有解决方案,使用product()chain()但在那里也没有成功。

Remember to wrap the x, y in parentheses this is the only slight caveat that if omitted leads to a SyntaxError . 请记住,将x, y括在括号中,这是唯一的警告,如果省略会导致SyntaxError

Other than that, the translation is pretty straightforward; 除此之外,翻译非常简单。 the order of the for s inside the comprehension is similar to that with the nested statements: 理解中for的顺序类似于嵌套语句的顺序:

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

Yields similar results to its nested loop counterpart: 产生与其嵌套循环副本类似的结果:

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

Below is the example to convert your code to list comprehension. 下面是将代码转换为列表理解的示例。

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

Alternatively, you achieve the same result using itertools library (sharing it just for your knowledge info, but is not recommended for this problem statement): 另外,您可以使用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)]

List comprehensions are designed to make a straightforward translation of that loop possible: 列表推导旨在使该循环的直接翻译成为可能:

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

Is that not what you wanted? 那不是你想要的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM