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
Python Program to print a specific number of rows with Maximum Sum
When working with a list of lists, you often need to find the rows with the highest sum values. Python provides an elegant solution using the sorted() method combined with a lambda function to sort rows by their sum in descending order.
Example
Below is a demonstration of finding the top 3 rows with maximum sum ?
my_list = [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]]
print("The list is:")
print(my_list)
my_key = 3
print("The number of top rows to select:")
print(my_key)
my_result = sorted(my_list, key=lambda row: sum(row), reverse=True)[:my_key]
print("The resultant list is:")
print(my_result)
The list is: [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]] The number of top rows to select: 3 The resultant list is: [[45], [2, 4, 6, 7], [1, 3, 5, 6]]
How It Works
The solution uses the following approach:
The
sorted()method sorts the list of lists based on a custom key functionThe
lambda row: sum(row)function calculates the sum of each rowThe
reverse=Trueparameter sorts in descending order (highest sum first)The slice
[:my_key]selects only the first 3 rows from the sorted result
Row Sum Breakdown
Let's analyze the sum of each row in our example:
my_list = [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]]
print("Row sums:")
for i, row in enumerate(my_list):
print(f"Row {i}: {row} ? Sum = {sum(row)}")
print("\nSorted by sum (descending):")
sorted_rows = sorted(my_list, key=lambda row: sum(row), reverse=True)
for i, row in enumerate(sorted_rows):
print(f"Rank {i+1}: {row} ? Sum = {sum(row)}")
Row sums: Row 0: [2, 4, 6, 7] ? Sum = 19 Row 1: [2, 4, 8] ? Sum = 14 Row 2: [45] ? Sum = 45 Row 3: [1, 3, 5, 6] ? Sum = 15 Row 4: [8, 2, 1] ? Sum = 11 Sorted by sum (descending): Rank 1: [45] ? Sum = 45 Rank 2: [2, 4, 6, 7] ? Sum = 19 Rank 3: [1, 3, 5, 6] ? Sum = 15
Alternative Approach Using heapq
For large datasets, you can use heapq.nlargest() for better performance ?
import heapq
my_list = [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]]
my_key = 3
result = heapq.nlargest(my_key, my_list, key=sum)
print("Top 3 rows with maximum sum:")
print(result)
Top 3 rows with maximum sum: [[45], [2, 4, 6, 7], [1, 3, 5, 6]]
Conclusion
Use sorted() with lambda for readable code when finding rows with maximum sum. For large datasets, consider heapq.nlargest() for better performance when you only need the top N rows.
