在列表元组中成对添加元素

时间:2018-09-10 19:56:23

标签: python python-3.x

我有两个元组列表

[[1,3000],[2,5000],[3,7000],[4,10000]]
[[1,2000],[2,3000],[3,4000],[4,5000]] 

总和为10000。这里我们有[2,5000],[4,5000]和[3,7000],[2,3000],因此输出应为 [2,4] [3,2]

[[1,2000],[2,4000],[3,6000]]
[[1,2000]]

总和为7000。在这里,由于我没有总和为7000的组合,因此考虑所有可能的组合4000(2000 + 2000),6000(4000 + 2000)和8000(6000 + 2000),然后考虑下一个期望的总和中的最小数字为6000。对于6000,我的输出应该是[2,4000]和[1,2000],它是 [2,1]

这是我的代码

import itertools

def optimalUtilization(maximumOperatingTravelDistance,
                       forwardShippingRouteList, returnShippingRouteList):
    result=[]
    t1=[]
    t2=[]
    for miles in forwardShippingRouteList:
        t1.append(miles[1])

    for miles in returnShippingRouteList:
        t2.append(miles[1])

    result.append(t1)
    result.append(t2)
    total_sum=set()

    for element in list(itertools.product(*result)):
        if sum(element)<=maximumOperatingTravelDistance:
            total_sum.add(sum(element))

    total_sum=sorted(total_sum,reverse=True)
    return optimalUtilizationhelper(total_sum[0],
                       forwardShippingRouteList, returnShippingRouteList)


def optimalUtilizationhelper(maximumOperatingTravelDistance,
                       forwardShippingRouteList, returnShippingRouteList):
    dist_dict={}
    for carid,miles in forwardShippingRouteList:
        dist_dict.update({miles:carid})

    result=[]

    for carid,miles in returnShippingRouteList:
        if (maximumOperatingTravelDistance-miles) in dist_dict:
            result.append(list((dist_dict[maximumOperatingTravelDistance-miles],carid)))

    return result

是否有更好的pythonic方法来做到这一点?

驱动程序代码

print(optimalUtilization(20,
                [[1,8],[2,7],[3,14]],
                [[1,5],[2,10],[3,14]]))

1 个答案:

答案 0 :(得分:1)

以下是组合数量的更简洁明了的描述:

from itertools import product

def optimalUtilization(n, l1, l2):
    # all (index1, index2, sum) triplets where sum is at most n
    res = [(a[0], b[0], a[1]+b[1]) for a, b in product(l1, l2) if a[1]+b[1] <= n]
    m = max(res, key=lambda x: x[2])[2]  # max sum <= n
    return [x[:2] for x in res if x[2] == m]

>>> optimalUtilization(20, [[1,8],[2,7],[3,14]], [[1,5],[2,10],[3,14]])
[(3, 1)]

它是更具可读性还是更Python化,无疑值得商::)

更新:不再需要排序和分组。