There is a list:
a = [("ax", 1), ("ec", 3), ("bk", 5)]
another list:
b = ["ec", "ax", "bk"]
I want to sort a
according to b
:
sort_it(a, b) a = [("ec", 3), ("ax", 1), ("bk", 5)]
How to do this?
Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.
Sorting a List by the Second Element of the Tuple. If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key. Unfortunately, Python does not allow you to specify the index of the sorting element directly.
The list. sort() method key parameter is set to lambda. The arguement x is the iterable element ( tuple ) to be sorted by the second element, the number. The lambda expression sorts the list by the second element of the tuple value and updates the original.
a.sort(key=lambda x: b.index(x[0]))
This sorts a
in-place using the the index in b
of the first element of each tuple from a
as the values it sorts on.
Another, possibly cleaner, way of writing it would be:
a.sort(key=lambda (x,y): b.index(x))
If you had large numbers of items, it might be more efficient to do things a bit differently, because .index()
can be an expensive operation on a long list, and you don't actually need to do a full sorting since you already know the order:
mapping = dict(a) a[:] = [(x,mapping[x]) for x in b]
Note that this will only work for a list of 2-tuples. If you want it to work for arbitrary-length tuples, you'd need to modify it slightly:
mapping = dict((x[0], x[1:]) for x in a) a[:] = [(x,) + mapping[x] for x in b]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With