Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 需要得到最高的组合_Python_Combinations - Fatal编程技术网

Python 需要得到最高的组合

Python 需要得到最高的组合,python,combinations,Python,Combinations,我有一个列表,我需要找到一些约束条件下的最高值组合: 例如,假设我有: 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以下 因此,可能的

我有一个列表,我需要找到一些约束条件下的最高值组合:

例如,假设我有:

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']或['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,))
来自itertools导入产品的

组合=列表(产品(lst1、lst2、lst3))
结果=[]
对于索引,枚举中的组合(组合):
第一次总计=0
第二个_总数=0
对于组合中的成员:
第一个_总数+=成员[1]
第二个_总数+=成员[2]
如果second_total我可以想出比你正在做的更有效的机制(例如,当总数已经超过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])
来自itertools导入产品的

def find_best(列表):
返回最大值(
(产品(*列表)中组合的组合,如果
总和(x[2]表示组合中的x)<400
),键=λ组合:
总和(x[1]表示组合中的x))
列表=[
[a',1100],[b',2200],[c',1.5300],
[d',1100],[e',2200],[f',1.5300],
[g',5100],[h',9200],[i',11500],
]
打印(查找最佳(列表))
#输出:
#(['a',1100],'d',1100],'g',5100])

根据您在问题中的输入,预期的输出是什么?(我听不懂你的解释。)也许这里的答案是
[['a',…],['d',…],['g',…]
?(三个列表中各有一个项目,每个项目的第三个元素的总和必须小于400,这是唯一合法的组合吗?),lst2和lst3,因此有9种可能的组合,以澄清这一点。