0

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.

1 Answer 1

4

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]]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.