无法理解for循环的变量片断。

问题描述 投票:0回答:1

最近,我发现Paul Panzer(最佳答案)发布的一段python代码,在 Python "星星和条形"

import itertools
bars = [0, 0, 0, 0, 0, 8]
result = [[bars[j+1] - bars[j] - 1 for j in range(5)] for bars[1:-1] in itertools.combinations(range(1, 8), 4)]

我无法理解变量的片断。bars[1:-1] 内的for循环。请帮助我。

两者的关系是什么?bars 和循环中的可迭代对象的成员?

python loops slice
1个回答
1
投票

在表达式中。

for foo in itertools.combinations(range(1, 8), 4)

itertools.combinations(range(1, 8), 4) 产生了4个项目的序列,这些项目被分配给了变量。foo. 你可以看到这一点,如果你只是打印 foo 循环中。

>>> for foo in itertools.combinations(range(1, 8), 4):
...     print(foo)
...
(1, 2, 3, 4)
(1, 2, 3, 5)
(1, 2, 3, 6)
(1, 2, 3, 7)
(1, 2, 4, 5)
(1, 2, 4, 6)
(1, 2, 4, 7)
(1, 2, 5, 6)
(1, 2, 5, 7)
(1, 2, 6, 7)
(1, 3, 4, 5)
(1, 3, 4, 6)
(1, 3, 4, 7)
(1, 3, 5, 6)
(1, 3, 5, 7)
(1, 3, 6, 7)
(1, 4, 5, 6)
(1, 4, 5, 7)
(1, 4, 6, 7)
(1, 5, 6, 7)
(2, 3, 4, 5)
(2, 3, 4, 6)
(2, 3, 4, 7)
(2, 3, 5, 6)
(2, 3, 5, 7)
(2, 3, 6, 7)
(2, 4, 5, 6)
(2, 4, 5, 7)
(2, 4, 6, 7)
(2, 5, 6, 7)
(3, 4, 5, 6)
(3, 4, 5, 7)
(3, 4, 6, 7)
(3, 5, 6, 7)
(4, 5, 6, 7)

如果你替换掉 foo 列表分片有4个元素长,那么这4个元素就会被分配到该分片上。

>>> bars = [0, 0, 0, 0, 0, 8]
>>> for bars[1:-1] in itertools.combinations(range(1, 8), 4):
...     print(bars)
...
[0, 1, 2, 3, 4, 8]
[0, 1, 2, 3, 5, 8]
[0, 1, 2, 3, 6, 8]
[0, 1, 2, 3, 7, 8]
[0, 1, 2, 4, 5, 8]
[0, 1, 2, 4, 6, 8]
[0, 1, 2, 4, 7, 8]
[0, 1, 2, 5, 6, 8]
[0, 1, 2, 5, 7, 8]
[0, 1, 2, 6, 7, 8]
[0, 1, 3, 4, 5, 8]
[0, 1, 3, 4, 6, 8]
[0, 1, 3, 4, 7, 8]
[0, 1, 3, 5, 6, 8]
[0, 1, 3, 5, 7, 8]
[0, 1, 3, 6, 7, 8]
[0, 1, 4, 5, 6, 8]
[0, 1, 4, 5, 7, 8]
[0, 1, 4, 6, 7, 8]
[0, 1, 5, 6, 7, 8]
[0, 2, 3, 4, 5, 8]
[0, 2, 3, 4, 6, 8]
[0, 2, 3, 4, 7, 8]
[0, 2, 3, 5, 6, 8]
[0, 2, 3, 5, 7, 8]
[0, 2, 3, 6, 7, 8]
[0, 2, 4, 5, 6, 8]
[0, 2, 4, 5, 7, 8]
[0, 2, 4, 6, 7, 8]
[0, 2, 5, 6, 7, 8]
[0, 3, 4, 5, 6, 8]
[0, 3, 4, 5, 7, 8]
[0, 3, 4, 6, 7, 8]
[0, 3, 5, 6, 7, 8]
[0, 4, 5, 6, 7, 8]

同样的4个元素,但是现在它们被分配到了中间的位置 bars,由分片表达式 bars[1:-1].

在你理解的范围内。bars 将在通过外循环时拥有这些值。 内部理解会生成另一个列表,该列表基于 bars 的外循环中。


0
投票

bars[1:-1] 基本上是指所有的列表项从index 1-1,其中 -1 表示最后一个指数。

所以如果 bars = [1,2,3,4,5], bars[1:-1] = [2,3,4]

© www.soinside.com 2019 - 2024. All rights reserved.