按给定索引的元素对列表中的元组进行排序和访问

我有一个列表,我想根据第二个索引对列表中的元组进行排序。

data = [[(7, -1), (8, 10), (9, 5), (10, 0.1), (11, -0.4)], [(7, -3), (8, -1), (9, 2), (10, 0.4), (11, -0.2)]]

sorted_by_second = sorted(data, key=lambda tup: tup[1])

print(sorted_by_second)

结果是:

[[(7, -3), (8, -1), (9, 2), (10, 0.4), (11, -0.2)], [(7, -1), (8, 10), (9, 5), (10, 0.1), (11, -0.4)]]

但是我试图得到:

[[(7, -1), (11, -0.4), (10, 0.1), (9, 5), (8, 10)], [(7, -3), (8, -1), (11, -0.2), (10, 0.4), (9, 2)]]

我还想提取特殊条件的像元:当像元中的第二个索引等于-1时,以及当第二个索引值最小且第二个最小值时。

喜欢:

[[(7, -1), (10, 0.1), (9, 5)], [(8, -1), (10, 0.4), (9, 2)]]

我怎样才能做到这一点?

评论
深井冰
深井冰

您的列表实际上是列表的列表,因此您需要对每个子列表进行排序:

data = [[(7, -1), (8, 10), (9, 5), (10, 0.1), (11, -0.4)], [(7, -3), (8, -1), (9, 2), (10, 0.4), (11, -0.2)]]
sorted_by_second = [sorted(x, key=lambda tup: tup[1]) for x in data]
sorted_by_second

[[(7, -1), (11, -0.4), (10, 0.1), (9, 5), (8, 10)],
  [(7, -3), (8, -1), (11, -0.2), (10, 0.4), (9, 2)]]
点赞
评论