我希望以下片段给我一个迭代器,从两个输入迭代的笛卡尔乘积产生对:
$ 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?
该文件说,笛卡尔积函数
the actual implementation does not build up intermediate results in memory.
Run Code Online (Sandbox Code Playgroud)
如何用发电机做到这一点?有人能给我看一个2个发生器的有限内存消耗的例子吗?
使用pythons itertools,我想在一堆列表的所有排列的外积上创建一个迭代器.一个明确的例子:
import itertools
A = [1,2,3]
B = [4,5]
C = [6,7]
for x in itertools.product(itertools.permutations(A),itertools.permutations(B),itertools.permutations(C)):
print x
Run Code Online (Sandbox Code Playgroud)
虽然这有效,但我想将其推广到任意列表列表.我试过了:
for x in itertools.product(map(itertools.permutations,[A,B,C])):
print x
Run Code Online (Sandbox Code Playgroud)
但它并没有按照我的意图行事.预期的产出是:
((1, 2, 3), (4, 5), (6, 7))
((1, 2, 3), (4, 5), (7, 6))
((1, 2, 3), (5, 4), (6, 7))
((1, 2, 3), (5, 4), (7, 6))
((1, 3, 2), (4, 5), (6, 7))
((1, 3, 2), (4, 5), (7, 6))
((1, 3, 2), (5, 4), (6, 7))
((1, 3, 2), …Run Code Online (Sandbox Code Playgroud)