Python的itertools产品内存消耗

ful*_*ton 13 python generator python-itertools

文件说,笛卡尔积函数

the actual implementation does not build up intermediate results in memory.
Run Code Online (Sandbox Code Playgroud)

如何用发电机做到这一点?有人能给我看一个2个发生器的有限内存消耗的例子吗?

NPE*_*NPE 9

查看模块的源代码,itertools.product()实际上将每个参数转换为元组:

// product_new() in itertoolsmodule.c
for (i=0; i < nargs ; ++i) {
    PyObject *item = PyTuple_GET_ITEM(args, i);
    PyObject *pool = PySequence_Tuple(item); //<==== Call tuple(arg)
    if (pool == NULL)
        goto error;
    PyTuple_SET_ITEM(pools, i, pool);
    indices[i] = 0;
}
Run Code Online (Sandbox Code Playgroud)

换句话说,itertools.product()在输入参数的大小中,内存消耗似乎是线性的.