简体   繁体   English

在Python中优化itertools排列

[英]Optimizing itertools permutations in Python

In context of memory management i face a lot of issues while using itertools permutations specially when the length of list is more than 10. 在内存管理的背景下,尤其是当列表长度超过10时,在使用itertools permutations时,我会遇到很多问题。

Is there any better way of generating permutations for any list such that memory is not much utilized ? 有没有更好的方法可以为任何列表生成排列,从而不占用大量内存?

Below is the way how i am using it. 以下是我使用它的方式。

     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)

If all you need to do is iterate over the permutations, don't store them. 如果您需要做的只是遍历排列,请不要存储它们。 Iterate directly over the object returned by itertools.permutations . 直接在itertools.permutations返回的对象上进行迭代。 In other words do this: 换句话说:

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

Calling list on an iterator is exactly the way to say "give me all of the elements right now in memory at the same time". 迭代器上的调用list正是这样说的:“同时将内存中的所有元素都给我”。 If you don't want or need all of them in memory at once, don't use list . 如果您不想一次或全部将它们存储在内存中,请不要使用list If you just want to use one element at a time, just iterate over what you want to iterate over. 如果您只想一次使用一个元素,则只需迭代要迭代的对象即可。

Note that your code will still take a long time to run if you really try to go through all the permutations, because 18! 请注意,如果您真的尝试遍历所有排列,您的代码仍将花费很长时间,因为18! is a really big number. 是一个很大的数字。

permutations returns a generator. 排列返回生成器。 So the solution is pretty much what you already wrote: 因此,解决方案几乎就是您已经写的:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM