Python sort nested list by second element
Ngày đăng:
08/12/2021
Trả lời:
0
Lượt xem:
121
Show Python program to sort a list according to the second element in the sublist.PythonProgrammingServer Side Programming List is given, our task is to sort a list according to the second element in the sublist. Here we apply simple bubble sort. ExampleInput : [['CCC', 15], ['AAA', 10], ['RRRR', 2],['XXXX', 150]] Output : [['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]AlgorithmStep 1: Given a list. Step 2: We have tried to access the second element of the sublists using the nested loops. Step 3: Traverse through all array elements. Step 4: Last i elements are already in place. Step 5: traverse the array from 0 to n-i-1. Step 6: Swap if the element found is greater than the next element.Example Code# Python program to sort the lists using the second element of sublist # In place way to sort, use of third variable. def sortlist(A): l = len(A) for i in range(0, l): for j in range(0, l-i-1): if (A[j][1] > A[j + 1][1]): tempo = A[j] A[j]= A[j + 1] A[j + 1]= tempo return A # Driver Code A = [['AAA', 10], ['CCC', 15], ['RRRR', 2], ['XXXX', 150]] print(sortlist(A))Output[['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]Rishi Raj Published on 26-Sep-2018 07:39:29 Previous Page Print Page Next Page Advertisements |