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
-
Economics & Finance
Selected Reading
Python program to sort table based on given attribute index
Suppose we have a 2D list containing information about athletes. This information includes rank, age, and height. Each row contains data for different athletes. We need to sort the table based on a given attribute index k.
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 (sort by age), then the output will be ?
| Rank | Age | Height |
|---|---|---|
| 1 | 25 | 190 |
| 4 | 26 | 175 |
| 3 | 33 | 185 |
| 2 | 35 | 180 |
| 5 | 35 | 180 |
Approach
To solve this problem, we will ?
- Use the
sort()method with a lambda function as the key parameter - The lambda function will extract the element at index
kfrom each row for comparison - The
sort()method will arrange rows in ascending order based on the kth attribute
Example
Let us see the following implementation to get better understanding ?
def solve(info, k):
info.sort(key=lambda x: x[k])
return info
# Sample data: [rank, age, height]
athletes_data = [[1, 25, 190], [2, 35, 180], [3, 33, 185], [4, 26, 175], [5, 35, 180]]
k = 1 # Sort by age (index 1)
result = solve(athletes_data, k)
print("Sorted by age:")
for row in result:
print(row)
Sorted by age: [1, 25, 190] [4, 26, 175] [3, 33, 185] [2, 35, 180] [5, 35, 180]
Sorting by Different Attributes
You can sort by any attribute by changing the value of k ?
def sort_table(data, attribute_index):
data.sort(key=lambda x: x[attribute_index])
return data
# Sample data
athletes = [[1, 25, 190], [2, 35, 180], [3, 33, 185], [4, 26, 175], [5, 35, 180]]
# Sort by rank (index 0)
print("Sort by rank:")
result1 = sort_table(athletes.copy(), 0)
print(result1)
# Sort by height (index 2)
print("\nSort by height:")
result2 = sort_table(athletes.copy(), 2)
print(result2)
Sort by rank: [[1, 25, 190], [2, 35, 180], [3, 33, 185], [4, 26, 175], [5, 35, 180]] Sort by height: [[4, 26, 175], [2, 35, 180], [5, 35, 180], [3, 33, 185], [1, 25, 190]]
Key Points
- The
lambda x: x[k]function extracts the element at indexkfrom each row - The
sort()method modifies the original list in-place - Use
list.copy()if you want to preserve the original data - The sorting is stable, meaning equal elements maintain their relative order
Conclusion
Sorting a 2D list by a specific attribute index is efficiently accomplished using Python's sort() method with a lambda function. This approach allows flexible sorting by any column index in the table.
Advertisements
