Python | Ways to sort a compressed list by value

Python Methods and Functions

Let's discuss a few methods to demonstrate the problem.

Method # 1: Using lambda and sorting

# Python code for demo
# sort the compressed list by value
# using a lambda and sorted

 
# Declaring initial lists

list1 = [ ' geeks' , 'for' , 'Geeks' ]

list2 = [ 3 , 2 , 1 ]

zipped = zip (list1, list2)

 
# Convert to list

zipped = list (zipped)

 
# Print archive

print ( "Initial zipped list -" , str (zipped))

 
# Using sorting and lambda

res = sorted (zipped, key = lambda x: x [ 1 ])

 
# print result

print ( " final list - " , str (res))

Exit:

 Initial zipped list - [(' geeks', 3), ('for', 2), (' Geeks', 1)] final list - [('Geeks', 1), (' for', 2), ('geeks', 3)] 

Method # 2: Using operator and sort

# Python code for the daemon strata
# sort the compressed list by values ​​
# using the operator and sorted

 

import operator

# Declaring initial lists

list1 = [ ' akshat' , 'Manjeet' , ' nikhil' ]

list2 = [ 3 , 2 , 1 ]

zipped = zip (list1, list2)

 
# Convert to list

zipped = list (zipped)

 
# Print archive

print ( "Initial zipped list -" , str (zipped))

  
# Using sort and operator

res = sorted (zipped, key = operator.itemgetter ( 1 ))

 
# print result

print ( " final list - " , str (res))

Exit:

 Initial zipped list - [('akshat', 3), (' Manjeet', 2), ('nikhil', 1)] final list - [(' nikhil', 1), ('Manjeet', 2), (' akshat' , 3)] 




Get Solution for free from DataCamp guru