我有一个列表[[['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))
请让我知道什么是最好的方式来实现这一点,通过列表理解排序
使用自定义函数
Ex:
输出:
相关问题 更多 >
编程相关推荐