Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
| Rank | age | height |
|---|---|---|
| 1 | 25 | 190 |
| 2 | 35 | 180 |
| 3 | 33 | 185 |
| 4 | 26 | 175 |
| 5 | 35 | 180 |
And k = 1.
then the output will be
| Rank | age | height |
|---|---|---|
| 1 | 25 | 190 |
| 4 | 26 | 175 |
| 3 | 33 | 185 |
| 2 | 35 | 180 |
| 5 | 35 | 180 |
[[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]]
Advertisements
