在长列表中查找所有元素组合的最有效方法 Python
Most effient way to find all combinations of elements in a long list Python
抱歉标题看起来有点far-fetched。我被要求计算列表中 2 个或更多元素的总和。我在网上搜索了一下,找到了一些结果,我测试了它们,但是没有用...
input.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 中的长列表中找到元素组合的最有效方法是什么”。
您可以尝试通过不将 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
抱歉标题看起来有点far-fetched。我被要求计算列表中 2 个或更多元素的总和。我在网上搜索了一下,找到了一些结果,我测试了它们,但是没有用...
input.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 中的长列表中找到元素组合的最有效方法是什么”。
您可以尝试通过不将 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