Python 如何在没有内存问题的情况下计算排列

Python 如何在没有内存问题的情况下计算排列,python,python-3.x,Python,Python 3.x,您好,我需要长度为m的列表l=[1,2,…,n]的所有置换 from itertools import permutations def calcPerm(l:list,m: int) perm=[] for i in permutations(l, m): perm.append(list((i))) 但是就像你看到的那样,足够大的记忆会爆炸 有没有一种方法我不必保存排列,这样我就可以使用每一个排列 立即但不要两次获得它们(例如[1,2]和[2,1]

您好,我需要长度为m的列表l=[1,2,…,n]的所有置换

from itertools import permutations
def calcPerm(l:list,m: int)
    perm=[]
    for i in permutations(l, m):
        perm.append(list((i)))
    
但是就像你看到的那样,足够大的记忆会爆炸

有没有一种方法我不必保存排列,这样我就可以使用每一个排列
立即但不要两次获得它们(例如[1,2]和[2,1]?

您必须使用
组合
,而不是
排列

from itertools import combinations, permutations
my_list = [1,2,3]
print(list(permutations(my_list, 2)))
#[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

print(list(combinations(my_list, 2)))
#[(1, 2), (1, 3), (2, 3)]

使用
itertools.compositions
并使用
yield
节省内存:

来自itertools导入组合的

def calcPerm(l:list,m:int):
对于组合中的i(l,m):
收益表((i))
对于calcPerm中的p(范围(10),5):
印刷品(p)

使用
calcPerm
作为生成器是您的选择吗?