![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to print a specific number of rows with Maximum Sum
When it is required to print a specific number of rows with the maximum sum, the ‘sorted’ method, and the ‘lambda’ method are used.
Example
Below is a demonstration of the same
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 key is") 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)
Output
The list is : [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]] The key is 3 The resultant list is : [[45], [2, 4, 6, 7], [1, 3, 5, 6]]
Explanation
A list of list is defined and is displayed on the console.
A key value is defined and is displayed on the console.
The ‘sorted’ method is used on the list along with the lambda method, where the sum of the elements is determined, and the elements are reversed based on the key value.
This is assigned to a variable.
This is displayed as output on the console.
Advertisements