列表中列表中的本地最大值

时间:2014-11-14 23:36:22

标签: python algorithm list nested-lists minimum

我有一个尝试使用较少种类产品的优化问题。

例如:

screws = [6,8,16,18,39]

我想将这5个螺丝换成3.所以我需要使用最强的螺丝,所以我可以选择[8,18,39]。使用任何其他选项将导致浪费 - 例如,螺钉16对于6的位置而言太强,因此[16,18,39]不是那么好。我想编写一个对大量零件也有用的算法。到目前为止,我试过这个:

def split_list(data, n):
    from itertools import combinations, chain
    for splits in combinations(range(1, len(data)), n-1):
        result = []
        prev = None
        for split in chain(splits, [None]):
            result.append(data[prev:split])
            prev = split
        yield result
new_list = list(split_list(screws, 3))       
#print list(split_list(screws, 3))

由于运行此代码,我得到了一个列表列表:

[[[6], [8], [16, 18, 39]], 
 [[6], [8, 16], [18, 39]], 
 [[6], [8, 16, 18], [39]], 
 [[6, 8], [16], [18, 39]], 
 [[6, 8], [16, 18], [39]], 
 [[6, 8, 16], [18], [39]]]

我想从所有列表中找出本地最大值。例如,在第一个列表[[6], [8],[16, 18, 39]]中,最大值= 6,最大值= 8,最大值= 39,依此类推。但我不知道该怎么做。有没有办法找到所有嵌套列表的局部最大值?我被困在这一刻,你能帮助我吗?我也希望有助于取得进一步进展。

稍后,我想检查同一列表中最大元素和其他元素之间的差异总和。所以,6-6 = 0,8-8 = 0,最后39-16 + 30-18-39-39 = 35.这将允许我找出所有列表列表中的最小值。这将是最佳解决方案。因此,最终结果应为[[6, 8], [16, 18], [39]],然后我会选择[8,18,39]

这基本上是我在教程和在线课程之后的第一个程序,所以非常欢迎所有帮助。

1 个答案:

答案 0 :(得分:0)

您有一个列表列表,因此只需迭代列表,然后获取子列表中每个子列表的最大值。

l = [[[6], [8], [16, 18, 39]],
 [[6], [8, 16], [18, 39]],
 [[6], [8, 16, 18], [39]],
 [[6, 8], [16], [18, 39]],
 [[6, 8], [16, 18], [39]],
 [[6, 8, 16], [18], [39]]]
for sub in l: # each sublist in l -> [[6], [8], [16, 18, 39]]etc..
    print([max(ele) for ele in sub]) # each sublist inside each sublist -> [6], [8], [16, 18, 39]

[6, 8, 39]
[6, 16, 39]
[6, 18, 39]
[8, 16, 39]
[8, 18, 39]
[16, 18, 39]

因此,在您的代码中,只需执行以下操作:

for sub in split_list(screws, 3):
    print([max(ele) for ele in sub])

要获得最大值减去每个元素,您将拥有许多嵌套循环:

l = [[[6], [8], [16, 18, 39]],
 [[6], [8, 16], [18, 39]],
 [[6], [8, 16, 18], [39]],
 [[6, 8], [16], [18, 39]],
 [[6, 8], [16, 18], [39]],
 [[6, 8, 16], [18], [39]]]

result = []
for sub in l:
    for sub_ele in sub:
        mx = max(sub_ele)
        result.append([mx]+map(lambda x: mx-x,sub_ele))


[[6, 0], [8, 0], [39, 23, 21, 0], [6, 0], [16, 8, 0], [39, 21, 0], [6, 0], [18, 10, 2, 0], [39, 0], [8, 2, 0], [16, 0], [39, 21, 0], [8, 2, 0], [18, 2, 0], [39, 0], [16, 10, 8, 0], [18, 0], [39, 0]]