Python Program to print a specific number of rows with Maximum Sum

PythonServer Side ProgrammingProgramming

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.

raja
Published on 14-Sep-2021 10:37:55
Advertisements