Python 列表排序使用 lambda 函数

我有一个清单[[['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))

请让我知道通过列表理解排序实现此目的的最佳方法是什么。


噜噜哒
浏览 88回答 1
1回答

收到一只叮咚

使用自定义函数前任: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]]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python