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) -->代表索引,索引(1) -->权重,索引(2) -->成本
例如[2,33.8,40] 2-->索引,33.8 -->权重,40-->成本
发布于 2021-08-17 07:12:27
这应该会有帮助:
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))https://stackoverflow.com/questions/68812763
复制相似问题