Python itertools.product冻结了更高的数字

时间:2016-10-16 12:32:26

标签: python python-3.x itertools

我有6个不同范围的变量。我想用我的代码创建可能性池。在这个例子中,我为每个变量提供了10个范围,但我必须给它们大约200个范围。但每当我试图超过20个范围(例如30个范围)时,Python就会自杀,有时它会冻结计算机。反正是为了让它更快更稳定吗?

感谢。

import itertools

a = [x for x in range(400,411)]
b = [x for x in range(400,411)]
c = [x for x in range(400,411)]
d = [x for x in range(400,411)]
e = [x for x in range(400,411)]
f = [x for x in range(400,411)]

fl = lambda x: x

it = filter(fl, itertools.product(a,b,c,d,e,f))

posslist = [x for x in it]

print(len(posslist))

4 个答案:

答案 0 :(得分:4)

共有6个列表,每个列表包含11个元素:[400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410]

6个这样的列表的笛卡尔积是11个 6 元组的列表,每个元素有6个整数(第一个元组是:(400, 400, 400, 400, 400, 400))。

64位Python * 中每个元组的大小为6 * 8字节。

所以posslist的总大小是6 * 8 * 11 6 = 81 GB!

你有足够的内存吗?可能不是,因此操作系统将开始交换RAM,这非常慢。因此,除了计算81 GB的数据外,计算机还必须不断地将数据从RAM交换到HDD并返回,因此它的工作速度会更慢。

*请注意,虽然它在32位Python中只有一半大小,但32位Python根本无法满足足够的内存

答案 1 :(得分:0)

使用here中的cartesian_product函数,距离itertools.product()

的速度提高近60倍
def cartesian_product2(arrays):

    la = len(arrays)
    arr = np.empty([len(a) for a in arrays] + [la])
    for i, a in enumerate(np.ix_(*arrays)):
        arr[...,i] = a

    return arr.reshape(-1, la)

答案 2 :(得分:0)

也许不是一次性完成所有操作,您可以尝试连续完成产品。例如,

import itertools as itt

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

fl = lambda x: x

s1 = filter(fl, itt.product(a, b))
s2 = filter(fl, itt.product(s1, c))

print(list(s2))

但结果如下所示。你只需要将元组的元组解压缩为一个元组。

[((1, 4), 7),
 ((1, 4), 8),
 ((1, 4), 9),
 ((1, 5), 7),
 ((1, 5), 8),
 ((1, 5), 9),
 ((1, 6), 7),
 ((1, 6), 8),
 ((1, 6), 9),
 ((2, 4), 7),
 ((2, 4), 8),
 ((2, 4), 9),
 ((2, 5), 7),
 ((2, 5), 8),
 ((2, 5), 9),
 ((2, 6), 7),
 ((2, 6), 8),
 ((2, 6), 9),
 ((3, 4), 7),
 ((3, 4), 8),
 ((3, 4), 9),
 ((3, 5), 7),
 ((3, 5), 8),
 ((3, 5), 9),
 ((3, 6), 7),
 ((3, 6), 8),
 ((3, 6), 9)]

我还认为,这可以并行化,您可以并行执行列表的产品。

对于列表L1,L2,L3,L4,执行以下操作:

th1_res = itertools.product(L1, L2)
th2_res = itertools.product(L3, L4)

thread_final = itertools.product(th1_res, th2_res)

答案 3 :(得分:0)

感谢大家的回答。在寻找更好的解决方案时,我找到了Python文档的答案。有一个关于使用itertools.product作为生成器而不是list的文档的示例。然而,我仍然无法找到让它更快的好主意。如果您要使用具有高价值的产品,这也将对您有所帮助。

Product generator for Python 2
Product generator for Python 3