2012-05-23 67 views
13

documentation說,笛卡爾積函數Python的itertools產品內存消耗

the actual implementation does not build up intermediate results in memory. 

怎麼可能可能的發電機?有人可以給我示例 有2個發電機有限的內存消耗?

+3

可能的重複[爲什麼我使用itertools.product獲取MemoryError?](http://stackoverflow.com/q/8695422/222914) –

回答

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; 
} 

換句話說,itertools.product()的內存消耗似乎是線性在輸入參數的大小。

4

嗯,它也說:

嵌套循環週期喜歡與推進在每個迭代上最右邊的元素 里程錶。此模式創建一個詞典 排序,以便如果輸入的可迭代序列被排序,產品 元組將按排序順序發出。

這幾乎是它如何工作的實施(Modules/itertoolsmodule.c

下面是狀態對象:

typedef struct { 
    PyObject_HEAD 
    PyObject *pools;  /* tuple of pool tuples */ 
    Py_ssize_t *indices; /* one index per pool */ 
    PyObject *result;  /* most recently returned result tuple */ 
    int stopped;   /* set to 1 when the product iterator is exhausted */ 
} productobject; 

而下一個項目是由函數product_next,使用這個返回狀態和報價中描述的算法來生成下一個狀態。請參閱this answer以瞭解內存要求。

對於普通教育,您可以閱讀有關如何使用C擴展here中的狀態創建發電機。