Open In App

Sort the values of first list using second list in Python

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two lists, sort the values of one list using the second list.

Examples: 

Input : list1 = [“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”, “i”]
           list2 = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]
Output : [‘a’, ‘d’, ‘h’, ‘b’, ‘c’, ‘e’, ‘i’, ‘f’, ‘g’]

Input : list1 = [“g”, “e”, “e”, “k”, “s”, “f”, “o”, “r”, “g”, “e”, “e”, “k”, “s”]
            list2 = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]
Output : [‘g’, ‘k’, ‘r’, ‘e’, ‘e’, ‘g’, ‘s’, ‘f’, ‘o’]

 

Approach : 
 

  1. Zip the two lists.
  2. Create a new, sorted list based on the zip using sorted().
  3. Using a list comprehension extract the first elements of each pair from the sorted, zipped list.

Concept : 
The purpose of zip() is to map a similar index of multiple containers so that they can be used just using as a single entity.
Below is the implementation of the above approach:
 

Python




# Python program to sort
# one list using
# the other list
 
 
def sort_list(list1, list2):
 
    zipped_pairs = zip(list2, list1)
 
    z = [x for _, x in sorted(zipped_pairs)]
 
    return z
 
 
# driver code
x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
y = [0,   1,   1,    0,   1,   2,   2,   0,   1]
 
print(sort_list(x, y))
 
x = ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"]
y = [0,   1,   1,    0,   1,   2,   2,   0,   1]
 
print(sort_list(x, y))


Output

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
['g', 'k', 'r', 'e', 'e', 'g', 's', 'f', 'o']

Time Complexity: O(nlogn)
Auxiliary Space: O(n)
In the above code, we have two lists, the first list is being sorted with respect to the values of the second list. 
 

y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Here first the lowest value is checked. Like in this list, 0 is the lowest, so starting from the first index, 0 is the lowest and it is at index 0. So the value of index 0 is stored at index 0 in the first list. Similarly, 0 is again found at index 3 and so the value of index 3 in the first list is index 1. The same goes until the list is not completed.
 

Approach 2: By using Dictionary, list comprehension, lambda function

Python3




def sorting_of_element(list1, list2):
 
    # initializing blank dictionary
    f_1 = {}
 
    # initializing blank list
    final_list = []
 
    # Addition of two list in one dictionary
    f_1 = {list1[i]: list2[i] for i in range(len(list2))}
 
    # sorting of dictionary based on value
    f_lst = {k: v for k, v in sorted(f_1.items(), key=lambda item: item[1])}
 
    # Element addition in the list
    for i in f_lst.keys():
        final_list.append(i)
    return final_list
 
 
list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
list2 = [0,   1,   1,    0,   1,   2,   2,   0,   1]
 
 
list3 = sorting_of_element(list1, list2)
print(list3)


Output

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Approach 3: Using sort(),list() and set() methods

Python3




# Python program to sort values of first list based on second list
list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
list2 = [0, 1, 1, 0, 1, 2, 2, 0, 1]
a = list(set(list2))
a.sort()
res = []
for i in a:
    for j in range(0, len(list2)):
        if(list2[j] == i):
            res.append(list1[j])
print(res)


Output

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

New Approach : Using collections.OrderedDict()

 Using OrderedDict() to store the mapping of list1 and list2, sorted() is used to sort the OrderedDict() on the basis of values from the second list and finally list() is used to get the result.
 

Python3




# Python program to sort values of first list based on second list
from collections import OrderedDict
list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
list2 = [0, 1, 1, 0, 1, 2, 2, 0, 1]
d = OrderedDict(zip(list1, list2))
res = list(OrderedDict(sorted(d.items(), key=lambda x: x[1])))
print(res)


Output

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Approach : Using the numpy.argsort() function with fancy indexing

note: install numpy module using command “pip install numpy”

The given methods are quite efficient, but we can use the numpy.argsort() function with fancy indexing to solve the problem more efficiently. Here is how we can implement it:

Algorithm:

Import numpy library.
Define a function sort_list that takes two lists list1 and list2 as input.
Get the indices that would sort the list2 using np.argsort(list2) and store it in idx.
Convert list1 to a numpy array, then use idx to sort it and return it.
 

Python3




import numpy as np
 
# Define a function that takes two lists as input, sorts the first list based on
# the order of the second list, and returns the sorted list as a numpy array
def sort_list(list1, list2):
    # Use numpy's argsort function to get the indices that would sort the second list
    idx = np.argsort(list2)
    # Index the first list using the sorted indices and return the result as a numpy array
    return np.array(list1)[idx]
 
# Define two lists of strings and integers to be used as inputs for the sort_list function
x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
y = [0, 1, 1, 0, 1, 2, 2, 0, 1]
 
# Call the sort_list function with the two lists and print the result
print(sort_list(x, y))
 
# Define another two lists of strings and integers to be used as inputs for the sort_list function
x = ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"]
y = [0, 1, 1, 0, 1, 2, 2, 0, 1]
 
# Call the sort_list function with the two lists and print the result
print(sort_list(x, y))


Output:

[‘a’ ‘d’ ‘h’ ‘b’ ‘c’ ‘e’ ‘i’ ‘f’ ‘g’]
[‘g’ ‘k’ ‘r’ ‘e’ ‘e’ ‘s’ ‘g’ ‘f’ ‘o’]

Time Complexity: O(nlogn) due to sorting operation using np.argsort().
Auxiliary Space: O(n) as we create a numpy array with the same size as list1.

This implementation is efficient as it leverages the optimized numpy library for sorting the array using argsort() function.



Previous Article
Next Article

Similar Reads

Sort the values of first list using second list
Given two lists, sort the values of one list using the second list. Examples: Input: list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]Output: [‘a’, ‘d’, ‘h’, ‘b’, ‘c’, ‘e’, ‘i’, ‘f’, ‘g’]Explanation: Since 'a', 'd' and 'h' have value = 0 in list 2, therefore they occur first, then 'b', 'c', 'e' and 'i' have
7 min read
Python | Largest, Smallest, Second Largest, Second Smallest in a List
Since, unlike other programming languages, Python does not have arrays, instead, it has list. Using lists is more easy and comfortable to work with in comparison to arrays. Moreover, the vast inbuilt functions of Python, make the task easier. So using these techniques, let's try to find the various ranges of the number in a given list. Examples: In
5 min read
Sort first k values in ascending order and remaining n-k values in descending order
Given an array of size n, arrange the first k elements of the array in ascending order and the remaining n-k elements in descending order. Examples: Input: arr[] = {5, 4, 6, 2, 1, 3, 8, 9, -1}, k = 4 Output: 2 4 5 6 9 8 3 1 -1 Input: arr[] = {5, 4, 6}, k = 2 Output: 4 5 6 Algorithm: Store the first k elements in an array and sort that in ascending
11 min read
Count ways to choose Triplets of Pairs such that either first or second values are distinct
Given an array of pairs arr[] of size N (N ? 3) where each element of pair is at most N and each pair is unique, the task is to determine the number of ways to select triplets from the given N pairs that satisfy at least one of the following conditions: The first value (a) of each pair should be distinct.The second value (b) of each pair should be
7 min read
Sort first half in ascending and second half in descending order | 1
Given an array of integers, sort the first half of the array in ascending order and second half in descending order. Examples: Input : arr[] = {5, 2, 4, 7, 9, 3, 1, 6, 8} Output : arr[] = {1, 2, 3, 4, 9, 8, 7, 6, 5} Input : arr[] = {1, 2, 3, 4, 5, 6} Output : arr[] = {1, 2, 3, 6, 5, 4}Recommended PracticeSort first half in ascending and second half
10 min read
Get Second Largest Number in Python List Using Bubble Sort
Finding the second-largest number in a list is a common programming task that involves sorting the list in ascending order. Bubble sort is a simple sorting algorithm that can be used for this purpose. In this article, we will explore the logic behind finding the second largest number using bubble sort and provide a Python program to implement it. M
3 min read
Python | Replace elements in second list with index of same element in first list
Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list. Method #1: Using Iteration C/C++ Code # Python code to replace every element # in second list with index of first element. # List Initialization Input1 = ['cut', 'god', 'pass']
5 min read
Sort an Array which contain 1 to N values in O(N) using Cycle Sort
Prerequisite: Cycle SortGiven an array arr[] of elements from 1 to N, the task is to sort the given array in O(N) time.Examples: Input: arr[] = { 2, 1, 5, 4, 3} Output: 1 2 3 4 5 Explanation: Since arr[0] = 2 is not at correct position, then swap arr[0] with arr[arr[0] - 1] Now array becomes: arr[] = {1, 2, 5, 4, 3}Now arr[2] = 5 is not at correct
6 min read
Python | Sort a list according to the second element in sublist
In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, the second by using the sort() method, and last but not the least by the use of the sorted() meth
9 min read
Python program to sort a list of tuples by second Item
Given a list of tuples, write a Python program to sort the tuples by the second item of each tuple. Examples: Input : [('for', 24), ('Geeks', 8), ('Geeks', 30)] Output : [('Geeks', 8), ('for', 24), ('Geeks', 30)] Input : [('452', 10), ('256', 5), ('100', 20), ('135', 15)] Output : [('256', 5), ('452', 10), ('135', 15), ('100', 20)] Method #1: Using
6 min read