Python program to sort table based on given attribute index


Suppose we have a 2d list containing information about athletes. This information is rank, age, height. Each row contains information for different athletes. We also have another number k. We have to sort the data based on kth attribute.

So, if the input is like

Rankageheight
125190
235180
333185
426175
535180

And k = 1.

then the output will be

Rankageheight
125190
426175
333185
235180
535180

[[1, 25, 190], [4, 26, 175], [3, 33, 185], [2, 35, 180], [5, 35, 180]]

To solve this, we will follow these steps −

  • Call the sort() function for the 2d array called info

  • define one function that sort based on kth argument and pass it to the key parameter of sort() function.

Example

Let us see the following implementation to get better understanding

def solve(info, k):
   info.sort(key = lambda x: x[k])
   return info

info = [[1, 25, 190],[2, 35, 180],[3, 33, 185],[4, 26, 175],[5, 35, 180]]
k = 1
print(solve(info, k))

Input

[[1, 25, 190],[2, 35, 180],[3, 33, 185],[4, 26, 175],[5, 35, 180]], 1

Output

[[1, 25, 190], [4, 26, 175], [3, 33, 185], [2, 35, 180], [5, 35, 180]]

Updated on: 12-Oct-2021

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements