我有嵌套列表,任务是找到最大成本,但如果两个成本是相同的,那么只保留一个权重较低的,并找到第二高的成本


ls = [[2, 33.8, 40], [3, 43.15, 10], [4, 37.97, 16], [5, 46.81, 36], [6, 48.77, 79], [8, 19.36, 79], [9, 6.76, 64]]
fn = [ls[0]]
for v in ls:
if v not in fn:            
if v[2] == fn[0][2]:
if (v[2]+v[1]) < (fn[0][1]+fn[0][2]) and len(fn) <=1:
fn.append(v)
else:
fn.append(v)
if v[2] != fn[0][2] and v[2] > fn[0][2]:
fn.pop(0)
fn.append(v)
print(fn)

结果是这样的= [[6,48.77,79],[8,19.36,79]]首先,我想只保留最小的权值,其中2个代价是相似的,找到2个最高的,并附加到fn。预计出把[[8,19.36,79],[9,6.76,64]]

在给定的列表中第一个索引(0)——>表示索引,index(1)——>权重,指标(2)—>成本

For and example[[2,33.8, 40]] 2—>指数,33.8 ->重量,40——比;成本

这应该有帮助:-

ls = [[2, 33.8, 40],
[3, 43.15, 10],
[4, 37.97, 16],
[5, 46.81, 36],
[6, 48.77, 79],
[8, 19.36, 79],
[9, 6.76, 64]]

def process(mls):
sl = sorted(mls, reverse=True, key=lambda x: (x[2], x[1]))
r = [sl[0], None]
while len(sl) > 2 and sl[0][2] == sl[1][2]:
r[0], r[1] = sl[1], sl[2]
sl.pop(0)
return [x for x in r if x is not None]

print(process(ls))

最新更新