简体   繁体   English

将所有组合存储在列表中时如何避免内存错误

[英]How to avoid memory error when storing all combinations in a list

I am generating all combinations from a set of numbers, and then want to generate combinations of those combinations. 我正在从一组数字生成所有组合,然后想要生成这些组合的组合。 Because of the vast number of possible combinations I keep getting a memory error. 由于存在大量可能的组合,因此我不断遇到内存错误。 I have looked at the following questions but none have really solved my problem: 我看过以下问题,但没有一个能真正解决我的问题:
Creating all combinations of a set and running out of memory 创建集合的所有组合并耗尽内存
Python itertools.combinations() memory problems Python itertools.combinations()内存问题
Python list memory error Python列表内存错误

I am generating my list using the following method: 我正在使用以下方法生成列表:

#generate all combinations of 1 and 0 of size 30
set_1 = itertools.product([0,1], repeat = 30)
#generate all combinations of set 1, of size 5
set_2 = [tuple(c) for c in pulp.allcombinations(set_1, 5)]
for sets in set_2:
    print(sets)

Them memory error occurs while it is generating set_2. 它们生成set_2时发生内存错误。 I would like to still be able to iterate over set_2 as I will need to access the sets later on. 我仍然希望能够遍历set_2,因为以后需要访问这些set。 I have considered writing the sets to a txt file, but I would like to save that as a last resort. 我曾考虑过将这些设置写入txt文件,但我想将其保存为万不得已。

Instead of using a list comprehension which creates a list in your memory you can use a generator expression to store set2 and save your memory: 可以使用生成器表达式存储set2并保存您的内存,而不是使用在列表中创建在内存中创建列表的列表理解:

set_2 = (tuple(c) for c in pulp.allcombinations(set_1, 5))

Generators are like list comprehension except that they doesn't store the values in memory and just produce the values on demand.But they are one shot iterators and you can not iterate over them again like the result of a list comprehension. 生成器类似于列表推导,不同之处在于它们不将值存储在内存中,仅根据需要生成值。但是它们是一次迭代的迭代器,您不能像列表推导的结果一样再次遍历它们。

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

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