Home >Backend Development >Python Tutorial >How to sort one list based on the value of another list in Python?

How to sort one list based on the value of another list in Python?

王林
王林forward
2023-09-12 11:09:081484browse

How to sort one list based on the value of another list in Python?

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 .

Sort a list by values ​​in another list

Example

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)

Output

List1 = 
 ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai']
List2 (indexes) = 
 [2, 5, 1, 4, 3]

Sorted List =  ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']

Use a dictionary to sort a list by values ​​in another list

Example

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)

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete