A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-sort-values-first-list-using-second-list/ below:

Sort the values of first list using second list in Python

Sort the values of first list using second list in Python

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() and sorted()

zip() function pairs elements from two lists and sorted() allows us to sort these pairs based on the second list.

Python
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)

Output
['b', 'd', 'a', 'c']

Explanation:

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.

Python
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)

Output
['b', 'd', 'a', 'c']

Explanation:

Using a Custom Sorting Function with 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.

Python
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)

Output
['Learn', 'Python', 'with', 'GFG']

Explanation:

Using 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:



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