我有一个列表列表,我需要在给定一些约束的情况下找到最高值组合:
例如,让我们说:lst1 = [['a', 1, 100], ['b', 2, 200], ['c', 1.5, 300]]
lst2 = [['d', 1, 100], ['e', 2, 200], ['f', 1.5, 300]]
lst3 = [['g', 5, 100], ['h', 9, 200], ['i', 11, 500]]
如果我想从每个列表中得到1个选项的组合,其中第二个值的总和最高,而第三个值的总和低于401.
所以可能的组合是['a', 'd', 'g'] or ['b', 'd', 'h']
。
是否有针对此优化的库,或者我需要执行以下操作:
from itertools import product
combinations = list(product(lst1, lst2, lst3))
outcomes = []
for index, combination in enumerate(combinations):
first_total = 0
second_total = 0
for member in combination:
first_total += member[1]
second_total += member[2]
if second_total <= 400:
outcomes.append((index, first_total,))
答案 0 :(得分:1)
我可以想到比你正在做的更多高效的机制(例如,当总数超过400时修剪),但我无法想出制作代码的方法更清楚。这是一个简短的工作版本,如果有帮助:
from itertools import product
def find_best(lists):
return max(
(combination for combination in product(*lists) if
sum(x[2] for x in combination) < 400
), key=lambda combination:
sum(x[1] for x in combination))
lists = [
[['a', 1, 100], ['b', 2, 200], ['c', 1.5, 300]],
[['d', 1, 100], ['e', 2, 200], ['f', 1.5, 300]],
[['g', 5, 100], ['h', 9, 200], ['i', 11, 500]],
]
print(find_best(lists))
# Output:
# (['a', 1, 100], ['d', 1, 100], ['g', 5, 100])