我有一個清單[[['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))請讓我知道通過列表理解排序實現此目的的最佳方法是什么。
1 回答

收到一只叮咚
TA貢獻1821條經驗 獲得超5個贊
使用自定義函數
前任:
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]]]
添加回答
舉報
0/150
提交
取消