- 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 Sort Matrix Rows by summation of consecutive difference of elements
Example
Below is a demonstration of the same
def diff_summation_elem(row): return sum([abs(row[index + 1] - row[index]) for index in range(0, len(row) - 1)]) my_list = [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5,62]] print("The list is : ") print(my_list) my_list.sort(key=diff_summation_elem) print("The resultant list is :" ) print(my_list)
Output
The list is : [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]] The resultant list is : [[71, 53, 34, 65], [15, 36, 5, 62], [97, 6, 47, 3], [6, 88, 3, 26]]
Explanation
A method named ‘diff_summation_elem’ is defined that takes a list as a parameter.
It uses the ‘abs’ method and the ‘sum’ method along with list comprehension to iterate over the list and get specific index values.
Outside the method, a list of list is defined and is displayed on the console.
The list is sorted based on the key being the method (previously defined).
The output is displayed on the console.
Advertisements