简体   繁体   中英

Python List Sorting using lambda function

I have a list as [[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]], [['bar', 'bro', 200], ['bar', '$total', -200], ['bar', 'sup', -400]]]

I want to apply a sorting list comprehension such that the "$total" comes first in the list and the rest of the list is sorted as per the third item in the list.

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

Here the "$total" comes first as per all the sub-lists and rest of the list is reversed sorted as per the last/third element.

I tried this but did not work:

 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))

Kindly let me know what would be the best way to achieve this via list comprehension sorting.

Using a custom function

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]

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM