限制python中组合/排列的数量

Des*_*Ice 2 python list permutation python-itertools

我将使用itertools生成一些组合,当我意识到随着元素数量的增加,所花费的时间将呈指数增长.我可以限制或指示要生成的最大排列数,以便itertools在达到该限制后停止.

我的意思是:

目前我有

#big_list is a list of lists
permutation_list = list(itertools.product(*big_list))
Run Code Online (Sandbox Code Playgroud)

目前,这种排列列表有超过600万个排列.我很确定如果我添加另一个列表,这个数字将达到十亿大关.

我真正需要的是大量的排列(比方说5000).有没有办法限制生成的permutation_list的大小?

the*_*eye 8

你需要itertools.islice像这样使用

itertools.islice(itertools.product(*big_list), 5000)
Run Code Online (Sandbox Code Playgroud)

它不会在内存中创建整个列表,但会返回一个迭代器,它会懒惰地使用实际的迭代.您可以将其转换为这样的列表

list(itertools.islice(itertools.product(*big_list), 5000))
Run Code Online (Sandbox Code Playgroud)