Python | Ways to sort a zipped list by values
Last Updated :
20 Apr, 2023
Zipped lists are those lists where several lists are mapped together to form one list which can be used as one entity altogether. In Python Zip() function is used to map different lists. Let’s discuss a few methods to demonstrate the problem.
Method #1: Using lambda and sort
Python3
list1 = [ 'geeks' , 'for' , 'Geeks' ]
list2 = [ 3 , 2 , 1 ]
zipped = zip (list1, list2)
zipped = list (zipped)
print ("Initial zipped list - ", str (zipped))
res = sorted (zipped, key = lambda x: x[ 1 ])
print ("final list - ", str (res))
|
Output:
Initial zipped list - [('geeks', 3), ('for', 2), ('Geeks', 1)]
final list - [('Geeks', 1), ('for', 2), ('geeks', 3)]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using operator and sort
Python3
import operator
list1 = [ 'akshat' , 'Manjeet' , 'nikhil' ]
list2 = [ 3 , 2 , 1 ]
zipped = zip (list1, list2)
zipped = list (zipped)
print ("Initial zipped list - ", str (zipped))
res = sorted (zipped, key = operator.itemgetter( 1 ))
print ("final list - ", str (res))
|
Output:
Initial zipped list - [('akshat', 3), ('Manjeet', 2), ('nikhil', 1)]
final list - [('nikhil', 1), ('Manjeet', 2), ('akshat', 3)]
Method #3: Using the zip and sorted functions with the key argument:
Approach:
- Zip the two lists together using the zip function
- Sort the zipped list using the sorted function with the key argument set to lambda x: x[1]
- Unzip the sorted zipped list using the zip function with the * operator
- Convert the unzipped result to a list
Python3
list1 = [ 1 , 3 , 5 , 7 ]
list2 = [ 2 , 4 , 6 , 8 ]
zipped = list ( zip (list1, list2))
sorted_zipped = sorted (zipped, key = lambda x: x[ 1 ])
sorted_list1, sorted_list2 = zip ( * sorted_zipped)
print ( list (sorted_zipped))
print ( list (sorted_list1))
print ( list (sorted_list2))
|
Output
[(1, 2), (3, 4), (5, 6), (7, 8)]
[1, 3, 5, 7]
[2, 4, 6, 8]
Time complexity: O(n log n)
Space complexity: O(n)
Share your thoughts in the comments
Please Login to comment...