在Python中优化itertools排列

时间:2015-09-27 06:46:29

标签: python algorithm python-3.x

在内存管理的上下文中,当列表长度超过10时,我在使用itertools permutations时遇到很多问题。

有没有更好的方法为任何列表生成排列,以至于内存利用率不高?

以下是我使用它的方式。

     num_list = [i for i in range(0,18)]
     permutation_list = list(permutations(num_list,len(num_list)))

     for p_tuples in permutation_list:
          print(p_tuples)

2 个答案:

答案 0 :(得分:2)

如果你需要做的就是迭代排列,不要存储它们。直接迭代itertools.permutations返回的对象。换句话说,这样做:

permutations = permutations(num_list,len(num_list))
for perm in permutations:
    doSomethingWith(perm)

在迭代器上调用list就是说“同时在内存中给我所有元素”的方式。如果您不想在内存中同时使用所有内容,请不要使用list。如果您只想一次使用一个元素,只需迭代您想要迭代的内容。

请注意,如果你真的试图通过所有的排列,你的代码仍然需要很长时间才能运行,因为18!是一个非常大的数字。

答案 1 :(得分:1)

排列返回一个生成器。所以解决方案 几乎就是你写的:

num_list = [i for i in range(0,18)]

for p_tuples in permutations(num_list,len(num_list)):
    print(p_tuples)