Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].
Order Tuples by List
We are given a list of tuples and a sorting list. We will create a python program for sorting list of tuples based on the values of the sorting list.
Input:
tupList = [('l', 5), ('k', 2), ('a', 1), ('e', 6)], sortList = ['l', 'a', 'k', 'e']
Output:
[('l', 5), ('a', 1), ('k', 2), ('e', 6)]
Method 1:
A method to sort the list of tuples based on a list is by creating an empty dictionary and storing all list elements as keys with empty value. Then feed values to the dictionary.
This is done using a combination of setdefault() + sorted() + lambda function.
Program:
Output:
Method 2:
Another method to sort the list of tuples is by creating a dictionary with values of the list of tuples. Then, we will use list comprehension to store the values of the dictionary sorted by using sorting list.
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer