您在生成器上调用list()。这将一次又一次地调用生成器,直到它耗尽。让我们跟踪执行流程。这是理解生成器的一个很好的练习。我会将所有内容格式化为代码块,以便我可以使用适当的缩进来阐明生成器调用的层次结构。
subsets([1, 2, 3]) is called,
so A is [1, 2, 3].
This list is not empty, so the else block is executed.
A[1:] is [2, 3], so to determine the first s,
subsets([2, 3]) is called.
Now A is [2, 3], so A[1:] is [3], so to determine s,
subsets([3]) is called.
Now A is [3], so A[1:] is [], so to determine s,
subsets([]) is called.
Now A is [], so the if block is executed.
This yields [].
The loop starts with s = [].
This yields [] again.
Now this loop starts, also with s = [],
because this is what subsets([3]) has just yielded.
So this yields [] as well.
So subsets([2, 3]) has yielded [],
so this loop also starts with s = [].
This yields [] yet again.
So subsets([1, 2, 3]) has yielded [],
and now this generator is called again (because of list()),
picking up the action after the previously executed yield statement.
So we reach the next statement: yield [A[0]] + s.
This yields [1].
subsets([1, 2, 3]) is called again,
picking up at the end of the first run through the for loop,
so to determine the next s,
subsets([2, 3]) is called again,
picking up at yield [A[0]] + s.
This yields [2].
So the loop starts again, with s = [2].
This yields [2].
subsets([1, 2, 3]) is called again,
picking up at yield [A[0]] + s, with s = [2].
This yields [1, 2].
subsets([1, 2, 3]) is called again,
picking up at the end of the for loop,
so to determine the next s,
subsets([2, 3]) is called again,
picking up at the end of the for loop,
so to determine the next s,
subsets([3]) is called again,
picking up at yield [A[0]] + s.
This yields [3].
So the loop starts again, with s = [3].
This yields [3].
So the loop starts again, with s = [3].
This yields [3].
subsets([1, 2, 3]) is called again,
picking up at yield [A[0]] + s, with s = [3].
This yields [1, 3].
subsets([1, 2, 3]) is called again,
picking up at the end of the for loop,
so to determine the next s,
subsets([2, 3]) is called again,
picking up at yield [A[0]] + s, with s = [3].
This yields [2, 3].
So the loop starts again, with s = [2, 3].
This yields [2, 3].
subsets([1, 2, 3]) is called again,
picking up at yield [A[0]] + s, with s = [2, 3].
This yields [1, 2, 3].
subsets([1, 2, 3]) is called again,
picking up at the end of the for loop,
so to determine the next s,
subsets([2, 3]) is called again,
picking up at the end of the for loop,
so to determine the next s,
subsets([3]) is called again,
picking up at the end of the for loop,
so to determine the next s,
subsets([]) is called again,
picking up at the end of the if block,
so we reach the end of the generator,
which means it is exhausted and yields nothing anymore.
So there is no further iteration of the for loop,
hence subsets([3]) is also exhausted.
So subsets([2, 3]) is also exhausted.
So subsets([1, 2, 3]) is also exhausted.