如何高效分析python中2个大列表的所有可能组合?

How to efficiently analyze all possible combinations of 2 large lists in python?

假设我们有 2 个列表,每个列表有大约 18 个完全不同的 1000 以下的号码。

现在,我们要计算每个列表中数字的所有可能组合(r 从 1 到 18)。

然后,我们要从列表中计算这些组合的所有可能对(对由列表 A 中的一个组合和列表 B 中的另一个组合组成) .

最后,假设我们要计算这些对之间的差异,方法是将对每一侧的所有数字相加,然后将对的第一个部分除以第二部分。最后,我们查看每次减法的结果并选择产生最大数字的对

我试图将所有对加载到一个大列表中,然后只做 for pair in list:,但是可能的对太多了,无法将它们全部加载到一个列表中。因此,我们必须在块中进行堡垒和分析对。但是,我不确定什么是最节省时间和资源的方法。

这是我尝试使用的代码示例:

from itertools import combinations, product
import random

list_A = random.sample(range(100, 250), 18)
list_B = random.sample(range(300, 450), 18)

# All possible combinations of items in list A
i = 1
all_list_A_combos = []
while i <= 18:
    all_list_A_combos_temp = combinations(list_A, i)
    all_list_A_combos.extend(all_list_A_combos_temp)
    i += 1

# All possible combinations of items in list B
i = 1
all_list_B_combos = []
while i <= 18:
    all_list_B_combos_temp = combinations(list_B, i)
    all_list_B_combos.extend(all_list_B_combos_temp)
    i += 1

# Executing this line crashes the program due to too many possible pairs
all_possible_pairs = list(product(all_list_A_combos, all_list_B_combos))

# Calculating products of division for each pair
list_of_all_differences = []
for pair in all_possible_pairs:

    side_A_sum = 0
    for number in pair[0]:
        side_A_sum += number
    side_B_sum = 0
    for number in pair[1]:
        side_B_sum += number

    difference = side_A_sum / side_B_sum
    list_of_all_differences.append(difference)

# Finding best pair
best_pair = all_possible_pairs[list_of_all_differences.index(max(list_of_all_differences))]
print(best_pair)

我知道您可以通过知道列表 A 中所有项目的总和除以列表 B 中的最小数字是正确答案来“作弊”,但我给出了除法的乘积作为任务的示例.在我的真实案例中,分析有点复杂,您需要扫描每个可能的对才能确定。

itertools 是基于生成器的。您很少需要将结果收集到列表中。制作你自己的发电机:

import itertools

def subset_pairs(list_a,list_b):
    """iterator over all pairs of subsets, (s,t), with s drawn from list_a and t drawn from list_b"""
    for i in range(1+len(list_a)):
        for j in range(1+len(list_b)):
            for s in itertools.combinations(list_a,i):
                for t in itertools.combinations(list_b,j):
                    yield s,t

这是一个简单的测试(使用 print 作为您处理的替身):

for s,t in subset_pairs(['a','b','c'],[1,2]):
    print(s,"and",t)

输出:

() and ()
() and (1,)
() and (2,)
() and (1, 2)
('a',) and ()
('b',) and ()
('c',) and ()
('a',) and (1,)
('a',) and (2,)
('b',) and (1,)
('b',) and (2,)
('c',) and (1,)
('c',) and (2,)
('a',) and (1, 2)
('b',) and (1, 2)
('c',) and (1, 2)
('a', 'b') and ()
('a', 'c') and ()
('b', 'c') and ()
('a', 'b') and (1,)
('a', 'b') and (2,)
('a', 'c') and (1,)
('a', 'c') and (2,)
('b', 'c') and (1,)
('b', 'c') and (2,)
('a', 'b') and (1, 2)
('a', 'c') and (1, 2)
('b', 'c') and (1, 2)
('a', 'b', 'c') and ()
('a', 'b', 'c') and (1,)
('a', 'b', 'c') and (2,)
('a', 'b', 'c') and (1, 2)