使用lambda函数的Python列表排序

2024-05-29 03:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表[[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]], [['bar', 'bro', 200], ['bar', '$total', -200], ['bar', 'sup', -400]]]

我想应用一个排序列表理解,这样“$total”在列表中排在第一位,列表的其余部分按照列表中的第三项进行排序

输出示例:[[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]], [['bar', '$total', -200], ['bar', 'bro', 200], ['bar', 'sup', -400]]]

在这里,根据所有子列表,“$total”排在第一位,而列表的其余部分则按照最后/第三个元素进行反向排序

我试过了,但没有成功:

 for index, ele in enumerate(final_res):
    final_res[index] = list(sorted(final_res[index], key=lambda x: [ x[1] if x[1] == "total" else x[2] ], reverse=True))

请让我知道什么是最好的方式来实现这一点,通过列表理解排序


Tags: 元素示例列表forindexfoo排序bar
1条回答
网友
1楼 · 发布于 2024-05-29 03:42:01

使用自定义函数

Ex:

data = [[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]], [['bar', 'bro', 200], ['bar', '$total', -200], ['bar', 'sup', -400]]] 
for i in data:
    i.sort(key=lambda x: (x[1] == '$total', x[2]), reverse=True)
print(data)
#OR data = [sorted(i, key=lambda x: (x[1] == '$total', x[2]), reverse=True) for i in data]

输出:

[[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]],
 [['bar', '$total', -200], ['bar', 'bro', 200], ['bar', 'sup', -400]]]

相关问题 更多 >

    热门问题