![]() |
VOOZH | about |
Given a list of tuples, our task is to reorder it according to the sequence defined in another list. This can be useful in data processing, sorting, and mapping tasks.
Example:
Input = [('Gfg', 10), ('best', 3), ('CS', 8), ('Geeks', 7)], ord_list = ['Geeks', 'best', 'CS', 'Gfg']
Output = [('Geeks', 7), ('best', 3), ('CS', 8), ('Gfg', 10)]
Convert the list of tuples into a dictionary for fast key-value access, then use list comprehension to reorder tuples based on the given list sequence.
[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]
Explanation:
This method builds a position map for elements using setdefault() and then sorts tuples with sorted() and a lambda based on that predefined order.
[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]
Explanation:
This method uses functools.reduce() to iterate over the order list and sequentially accumulate tuples from the main list in the desired order.
[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]
Explanation: reduce(lambda acc, key: acc + [ele for ele in t if ele[0] == key], l, []): iterates through each element in l, finds matching tuples in t, and accumulates them in order.
This method sorts the tuples based on the position of their first element in the reference list using a lambda function with sorted().
[('Geeks', 7), ('best', 3), ('CS', 8), ('Gfg', 10)]
Explanation: sorted(t, key=lambda x: l.index(x[0])): sorts t based on each tuple’s first element’s position in l.
This method sorts tuples based on a specific element index using itemgetter() from the operator module for cleaner and faster key access.
[('Geeks', 2), ('Gfg', 3), ('best', 9), ('CS', 10)]
Explanation:sorted(l1, key=itemgetter(1)): sorts the list based on the second element (index 1) of each tuple.