【问题标题】:Most effient way to find all combinations of elements in a long list Python在长列表Python中查找所有元素组合的最有效方法
【发布时间】:2021-05-21 07:00:08
【问题描述】:

抱歉,标题看起来有点牵强。我被要求计算列表中 2 个或更多元素的总和。我在网上搜索了一下,找到了一些结果,我测试了它们,但是没有用...

输入.txt

35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576

code.py

from itertools import combinations
  
def combo(arr, r):
  return list(combinations(arr, r))

with open("input.txt") as f:
  nums = f.read().split("\n")
  nums = [int(item) for item in nums]

r = range(2,20)
for rr in r:
  for c in combo(nums, rr):
    if sum(c) == 127:
        print(c)

它在上面的代码中有效,因为列表很短。但是,我收到的input.txt 有 100 行长!在这种情况下,Python 抛出了 MemoryError。所以我需要找到更好的方法。不幸的是,我没有找到任何其他方法,除了更长的方法,所以我问了一个问题,“在 Python 中找到长列表中元素组合的最有效方法是什么”。

【问题讨论】:

    标签: python-3.x list out-of-memory combinations long-integer


    【解决方案1】:

    您可以尝试通过不将itertools.combinations 的输出转换为列表而只是迭代生成器输出来节省内存:

    for rr in range(2, 22):
        print(f"combine {rr} values")
        for c in itertools.combinations(values, rr):
            if sum(c) == 127:
                print(c)
    

    检查:Making all possible combinations of a list

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 2010-09-29
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      相关资源
      最近更新 更多