将所有组合存储在列表中时如何避免内存错误
How to avoid memory error when storing all combinations in a list
我正在从一组数字生成所有组合,然后想生成这些组合的组合。由于可能的组合数量众多,我不断收到内存错误。我查看了以下问题,但 none 确实解决了我的问题:
Creating all combinations of a set and running out of memory
Python itertools.combinations() memory problems
我正在使用以下方法生成列表:
#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)
它们在生成时发生内存错误set_2。我希望仍然能够遍历 set_2,因为稍后我需要访问这些集合。我考虑过将集合写入 txt 文件,但我想将其保存为最后的手段。
您可以使用生成器表达式来存储 set2
并节省您的记忆,而不是使用在您的记忆中创建列表的列表理解:
set_2 = (tuple(c) for c in pulp.allcombinations(set_1, 5))
生成器就像列表推导式,只是它们不将值存储在内存中,只是在 demand.But 上生成值它们是一次性迭代器,您不能像 a 的结果一样再次迭代它们列表理解。
我正在从一组数字生成所有组合,然后想生成这些组合的组合。由于可能的组合数量众多,我不断收到内存错误。我查看了以下问题,但 none 确实解决了我的问题:
Creating all combinations of a set and running out of memory
Python itertools.combinations() memory problems
我正在使用以下方法生成列表:
#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)
它们在生成时发生内存错误set_2。我希望仍然能够遍历 set_2,因为稍后我需要访问这些集合。我考虑过将集合写入 txt 文件,但我想将其保存为最后的手段。
您可以使用生成器表达式来存储 set2
并节省您的记忆,而不是使用在您的记忆中创建列表的列表理解:
set_2 = (tuple(c) for c in pulp.allcombinations(set_1, 5))
生成器就像列表推导式,只是它们不将值存储在内存中,只是在 demand.But 上生成值它们是一次性迭代器,您不能像 a 的结果一样再次迭代它们列表理解。