We can sort a list by the values in another list by setting the second list to the index number of the value in the first list in sorted order .
In this example, we will sort the list based on the values in another list, i.e. the indexes of the second list will be in the order they are placed in the sorted order -
# Two Lists list1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] list2 = [2, 5, 1, 4, 3] print("List1 = \n",list1) print("List2 (indexes) = \n",list2) # Sorting the List1 based on List2 res = [val for (_, val) in sorted(zip(list2, list1), key=lambda x: x[0])] print("\nSorted List = ",res)
List1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] List2 (indexes) = [2, 5, 1, 4, 3] Sorted List = ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']
In this example, we will sort one list by the value of another list. We add these two lists to a dictionary and then sort them using the key values and lambdas in the dictionary.
# Two Lists list1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] list2 = [2, 5, 1, 4, 3] print("List1 = \n",list1) print("List2 (indexes) = \n",list2) # Blank dictionary newDict = {} # Blank list outList = [] # Both the lists in our dictionary newDict newDict = {list1[i]: list2[i] for i in range(len(list2))} # Sorting using the sorting() based on key and values # Using lambda as well s = {k: v for k, v in sorted(newDict.items(), key=lambda item: item[1])} # Element addition in the list for i in s.keys(): outList.append(i) print("\nSorted List = \n",outList)
List1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] List2 (indexes) = [2, 5, 1, 4, 3] Sorted List = ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']
The above is the detailed content of How to sort one list based on the value of another list in Python?. For more information, please follow other related articles on the PHP Chinese website!