python itertools组合逻辑

标签 python environment-variables python-itertools scopes

我正在查看 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/

相关文章:

iphone - 如何在命令行实用程序中获取不同版本的XCode的路径?

python - 从元组转换为 pydantic 模型

检查 env 是否为空

python - 序列化 C++ 对象以通过套接字发送到 Python - 最佳方法?

c - 须藤环境变量

python - 为什么一个 itertools.groupby 分组只能迭代一次?

python - Python的itertools.count怎么可能不增加?

python - 在Python中生成特定的列表组合

Python 类型提示 : when to use MutableSequence vs List

Python : 2d contour plot from 3 lists : x, y 和 rho?