Python Program to Sort the list according to the column using lambda
Last Updated :
25 Apr, 2023
Given a list, the task is to sort the list according to the column using the lambda approach. Examples:
Input : array = [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Output : Sorted array specific to column 0, [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Sorted array specific to column 1, [[2, 1, 2], [3, 2, 1], [1, 3, 3]] Sorted array specific to column 2, [[3, 2, 1], [2, 1, 2], [1, 3, 3]] Input : array = [[‘java’, 1995], [‘c++’, 1983], [‘python’, 1989]] Output : Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]] Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]
Approach:
- sorted() built-in function in Python gives a new sorted list from an iterable.
- key parameter to specify a function to be called on each list element prior to making comparisons.
- lambda is used as a function to iterate on each element.
- key = lambda x:x[i] here i is the column on which respect to sort the whole list.
Below is the implementation.
Python3
def sortarray(array):
for i in range ( len (array[ 0 ])):
sortedcolumn = sorted (array, key = lambda x:x[i])
print (" Sorted array specific to column {}, \
{}". format (i, sortedcolumn))
if __name__ = = '__main__' :
array = [[ 'java' , 1995 ], [ 'c++' , 1983 ],
[ 'python' , 1989 ]]
sortarray(array)
|
Output:
Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]] Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]
Time complexity: O(n*logn), as sorting is done.
Auxiliary Space: O(n),where n is length of array.
Please Login to comment...