我正在查看 itertools 的 python 文档中的组合代码 ( https://docs.python.org/2/library/itertools.html )
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
在索引[i] += 1的行上,为什么它能够找到'i'?据我了解,一旦退出 for 循环(在 while True 之后开始),变量“i”就不应该存在(就像第一个yield 语句中提到的 i 一样)!!!
谁能用英语解释一下逻辑?我明白,直到第一次产量,但后来我迷路了。提前致谢。
最佳答案
Python 不是 block 作用域的。粗略地说,Python 是函数作用域的。在其他语言中,如果您这样做了
for (int i = 0; i < whatever; i++) {
...
}
那么 i
将位于 for
循环的本地。在 Python 中,等价
for i in xrange(whatever):
使用整个封闭函数的局部变量i
。另外,i
永远不会取值 whatever
,因此当循环结束时,我们仍然有 i ==whatever - 1
。
关于python itertools组合逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30987241/