从前一个问题我学到了一些有趣的东西.如果Python itertools.product是由一系列迭代器提供的,那么这些迭代器将在笛卡尔积开始之前转换为元组.相关 问题查看源代码,itertools.product得出结论:虽然没有中间结果存储在内存中,但是在产品迭代开始之前创建了原始迭代器的元组版本.
问题:当(元组转换的)输入太大而无法保存在内存中时,有没有办法为笛卡尔积创建迭代器?琐碎的例子:
import itertools
A = itertools.permutations(xrange(100))
itertools.product(A)
Run Code Online (Sandbox Code Playgroud)
一个更实际的用例将采用一系列(*iterables[, repeat])类似于函数的原始实现 - 上面只是一个例子.它看起来不像你可以使用当前的实现itertools.product,所以我欢迎在纯python中提交(虽然你不能击败C后端itertools!).
我希望以下片段给我一个迭代器,从两个输入迭代的笛卡尔乘积产生对:
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> one = xrange(0, 10**9)
>>> two = (1,)
>>> prods = itertools.product(one, two)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
Run Code Online (Sandbox Code Playgroud)
相反,我得到了一个MemoryError.但我认为itertools.product没有将中间结果存储在内存中,那么是什么导致了MemoryError?