我有一个尝试使用较少种类产品的优化问题。
例如:
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]]
中,maximum = 6,maximum = 8,maximum = 39,等等。但我不知道该怎么做。有没有办法找到所有嵌套列表的局部最大值?我陷入了这一刻,你能帮帮我吗?我也希望能帮助您取得进一步的进展。
稍后,我想检查同一列表中最大值和其他元素之间的差值之和。因此,6-6 = 0、8-8 = 0,最后 39-16+30-18-39-39 = 35。这将使我能够从所有列表列表中找出最小值。这将是最优的解决方案。所以最终结果应该是 [[6, 8], [16, 18], [39]]
我会从中选择 [8,18,39]
.
这基本上是我在教程和在线类(class)之后的第一个程序,因此非常欢迎所有帮助。
最佳答案
您有一个列表列表的列表,因此只需遍历该列表,然后获取子列表中每个子列表的最大值。
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]]
关于python - 列表内列表的局部最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940612/