Sorting a list based upon values in an external list (Python)

list, python, sorting

Solution

Use `list.index` in the key:

>>> data = [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1],
            [5, .77, 1], [6, .98, 2]]
>>> List_1 = [2, 0, 1]
>>> sorted(data, key=lambda e: (List_1.index(e[2]), -e[1]))
[[6, 0.98, 2], [2, 0.49, 2], [3, 0.98, 0], [1, 0.45, 0],
 [4, 0.82, 1], [5, 0.77, 1]]

Problem

This query is somewhat related to this earlier one on sorting where, it was required to sort the following list, `data = [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2] ]` first by the values of the last member of the inner list like this way, `[[1, .45, 0], [3, .98, 0],[4, .82, 1], [5, .77, 1], [2, .49, 2], [6, .98, 2]]` and then sort within the sub-lists i.e. first sort the list with its last member as `'0'` using the middle member as the key, in descending order, then the sub-list with last member as `'1'` and so on. Now, instead of first sorting by the values of the last member, I would like like to sort based upon the order of these elements present in an external list. i.e. if the external list is List_1 ``` `List_1 = [2, 0, 1]` ``` Sorting should produce ``` [[2, .49, 2], [6, .98, 2] [1, .45, 0], [3, .98, 0], [4, .82, 1], [5, .77, 1]] ``` Finally, sorting the sub-lists based upon the middle element in descending order should produce: ``` [ [6, .98, 2],[2, .49, 2], [3, .98, 0], [1, .45, 0], [4, .82, 1], [5, .77, 1]] ``` Any suggestions on how to go about this ?

Original source

Related problems