Last Updated : 24 Dec, 2024
Sorting the values of the first list using the second list in Python is commonly needed in applications involving data alignment or dependency sorting. In this article, we will explore different methods to Sort the values of the first list using the second list in Python.
Using zip() andsorted()
zip()
function pairs elements from two lists and sorted()
allows us to sort these pairs based on the second list.
a = ['a', 'b', 'c', 'd']
b = [3, 1, 4, 2]
# Sort a using b
x = [val for _, val in sorted(zip(b, a))]
print(x)
['b', 'd', 'a', 'c']
Explanation:
zip(b, a)
pairs the elements of the second list (b
) with the first list (a
).sorted()
sorts these pairs based on the first element (from list b
).a.
Let's see some more methods and see how we can sort the values of one list using another list in Python
Using numpy.argsort()
If working with numerical lists, numpy.argsort()
provides a fast way to obtain indices for sorting.
import numpy as np
a = ['a', 'b', 'c', 'd']
b = [3, 1, 4, 2]
# Sort list_a using numpy.argsort()
sorted_a = [a[i] for i in np.argsort(b)]
print(sorted_a)
['b', 'd', 'a', 'c']
Explanation:
b
.a
.sort()
For a more manual approach, we can use a custom sorting function with sorted(). This method involves sorting list
by using a custom sorting function.
a = ['with', 'GFG', 'Learn', 'Python']
b = [3, 4, 1, 2]
# Using sort() with a custom sorting function
list1_sorted = sorted(a, key=lambda x: b[a.index(x)])
print(list1_sorted)
['Learn', 'Python', 'with', 'GFG']
Explanation:
sorted()
function is used with a custom key
function.a'
and mapping it to the corresponding value in 'b'
.Pandas
For tabular data or scenarios involving data frames, pandas provides a convenient way to sort one column based on another.
Python
import pandas as pd
a = ['a', 'b', 'c', 'd']
b = [3, 1, 4, 2]
# Create a DataFrame
df = pd.DataFrame({'a': a, 'b': b})
# Sort by column 'b' and extract 'a'
sorted_a = df.sort_values('b')['a'].tolist()
print(sorted_a)
Output:
['b', 'd', 'a', 'c']
Explanation:
a
and b
as columns.()
method sorts based on column b
.a
column is converted back to a list.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4