Python | Sort Reduce list by list

Python Methods and Functions

Method # 1: Using sorted () + list comprehension
This idea is similar to flattening a list of lists, but in addition we add a sorted function to sort the returned antialiased list, done by list comprehension.

# Python3 demo code
# sort list of lists
# using sorted + comprehension list

 
# list list initialization

test_list = [[ 3 , 5 ], [ 7 , 3 , 9 ], [ 1 , 12 ] ]

 
# print the original list of the list

print ( "The original list:" + str (test_list))

 
# using a sorted + comprehension list
# sort the list of lists

res = sorted ([j for i in test_list for j in i])

 
# result print

print ( "The sorted and flattened list: " + str (res))

Output:

 The original list: [[3 , 5], [7, 3, 9], [1, 12]] The sorted and flattened list: [1, 3, 3, 5, 7, 9, 12] 

Method # 2: Using itertools.chain () + sorted ()
The task that was done with the above list can also be done using the chaining function, which concatenates the elements of the list and then the sorted function performs the sorting task.

# Python3 demo code
# sort the list of lists
# using itertools.chain () + sorted ( )

from itertools import chain

 
# list list initialization

test_list = [[ 3 , 5 ], [ 7 , 3 , 9 ], [ 1 , 12 ]]

 
# print the original list of the list

print ( "The original list:" + str (test_list))

 
# using itertools.chain ( ) + sorted ()
# sort the list of lists

res = sorted (chain ( * test_list))

 
# print result

print ( " The sorted and flattened list: " + str (res))

Output:

 The original list: [[3, 5], [7, 3, 9], [1, 12]] The sorted and flattened list: [1, 3, 3, 5, 7, 9, 12] 




Get Solution for free from DataCamp guru