Table of Contents
Introduction
In this section of python programming, we will understand the concept to sort the list based on the elements of the second list.
Program
-
Using zip()
def sort_list(list1, list2): zip_list = zip(list2, list1) x = [i for _, i in sorted(zip_list)] return x list1 = ['v', 'i', 'b', 'g', 'y', 'o', 'r'] list2 = [0, 2, 1, 1, 2, 0, 1] print("Sorted list", sort_list(list1, list2))
Output
-
Using Dictionary, list comprehension and lambda function
def sort_list(list1, list2): # Blank dictionary and list new_dict = {} new_list = [] # Adding list1 and list2 new_dict = {list1[i]: list2[i] for i in range(len(list2))} # Sorting new_dict = {j : k for j, k in sorted(new_dict.items(), key = lambda item: item[1])} # Append element in the list for i in new_dict.keys(): new_list.append(i) return new_list list1 = ['red', 'yellow', 'black', 'blue', 'green', 'orange' ] list2 = [00, 2, 1, 1, 2, 0] print("Sorted list", sort_list(list1, list2))
Output
Explanation
In the above python codes, we have used two approaches: 1. Using zip() function and 2. Using Python Dictionary, list comprehension and lambda function.
In approach 1, we zipped two lists (list1 and list2) using zip(). The zip() function maps the elements of similar index. The new sorted list is obtained using sorted() function on zipped list. The next step is to obtain the first lowest element of each pair, this is done by using list comprehension. And the sorted list is displayed on the screen.
From output, we can see that values are printed in ascending order of index values and alphabetical ordering. The first element is ‘v’ having the lowest index 0 and also ‘o’ has index value 0, but still ‘o’ is printed before ‘v’ because of the alphabetical ordering.
In approach 2, we have initialized dictionary new_dict and list new_list with empty values and added the elements of both the lists in the dictionary. By using list comprehension and lambda function we sorted the elements based on key-value and append the elements in the list. The list is printed with the help of print() function.
We can see that the output of the second approach is something different. The difference is sorted list is only based on the index and follows left to right sorting of elements. The alphabetical ordering is not considered in this.
0 Comments