【问题标题】:How to avoid memory error when storing all combinations in a list将所有组合存储在列表中时如何避免内存错误
【发布时间】:2015-07-15 14:04:32
【问题描述】:

我正在从一组数字中生成所有组合,然后想要生成这些组合的组合。由于有大量可能的组合,我不断收到内存错误。我查看了以下问题,但没有一个真正解决了我的问题:
Creating all combinations of a set and running out of memory
Python itertools.combinations() memory problems
Python list memory error

我正在使用以下方法生成我的列表:

#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 文件,但我想将其保存为最后的手段。

【问题讨论】:

    标签: python memory combinations itertools pulp


    【解决方案1】:

    您可以使用生成器表达式来存储set2 并节省您的内存,而不是使用在您的记忆中创建列表的列表推导:

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

    生成器类似于列表推导,除了它们不将值存储在内存中,而是按需生成值。但是它们是一次性迭代器,您不能像列表推导的结果一样再次迭代它们。

    【讨论】:

    • 谢谢,这解决了集合生成问题。不幸的是,在我的代码中的另一部分,我创建了一个像这样的 LpVariable:` x = pinch.LpVariable.dicts("sets", set_2, lowBound = 0, upBound = 1, cat = pinch.LpInteger) ` 现在抛出一个内存错误
    • 你能让pulp.LpVariable.dicts返回一个生成器吗?
    • 我不这么认为,我需要创建一个字典来告诉我在LP问题的整体解决方案中使用了哪些集合。
    猜你喜欢
    • 2023-03-18
    • 2010-11-09
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多