我需要生成itertool.permutation
生成的列表的产品,并使用下面的代码:itertools.product:如何提高性能?
def iter_version():
l = [itertools.permutations(range(10)) for _ in range(10)]
g = itertools.product(*l)
for i in g:
yield i
但是这个代码是太慢。我的桌面上需要16秒钟。 cProfile除了告诉我这个函数需要16秒钟之外什么也没有显示。
如果我只是创造一些像这样疯狂的for循环:
def for_loop():
l = [itertools.permutations(range(10)) for _ in range(10)]
for i0 in l[0]:
for i1 in l[1]:
for i2 in l[2]:
for i3 in l[3]:
for i4 in l[4]:
for i5 in l[5]:
for i6 in l[6]:
for i7 in l[7]:
for i8 in l[8]:
for i9 in l[9]:
yield (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9)
这将运行几乎瞬间。
在我的情况下,排列生成器列表不是固定大小,所以我不能使用for循环版本。
谢谢@DSM。 'next(iter_version())'在我的桌面上需要16秒钟。我在Python的问题追踪器上发现了这个错误:http://bugs.python.org/issue10109 itertools.product会将迭代器先转换为列表,而不是稍后再做。 – yegle 2014-10-02 01:57:50
我发现了一个解决方案,我的具体用例,我会在下面发布。 – yegle 2014-10-02 01:58:38