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

王林
Release: 2023-09-12 11:09:08
forward
1398 people have browsed it

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)
Copy after login

Output

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

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)
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!