When it is required to sort matrix based on palindrome count, a method is defined that takes a list as parameter. It uses the list comprehension and ‘join’ method to iterate and see if an element is a palindrome or not. Based on this, results are determined and displayed.
Example
Below is a demonstration of the same
def get_palindrome_count(row): return len([element for element in row if''.join(list(reversed(element))) == element]) my_list = [["abcba", "hdgfue", "abc"], ["peep"],["py", "is", "best"],["sees", "level", "non", "noon"]] print("The list is :") print(my_list) my_list.sort(key=get_palindrome_count) print("The resultant list is :") print(my_list)
Output
The list is : [['abcba', 'hdgfue', 'abc'], ['peep'], ['py', 'is', 'best'], ['sees', 'level', 'non', 'noon']] The resultant list is : [['py', 'is', 'best'], ['abcba', 'hdgfue', 'abc'], ['peep'], ['sees', 'level', 'non', 'noon']]
Explanation
A method named ‘get_palindrome_count’ is defined that takes a list as parameter.
List comprehension is used to iterate over the list and see if the element is a palindrome or not.
If yes, it is returned.
Outside the method, a list of list with string values is defined and is displayed on the console.
The ‘sort’ method is used to sort the list based on the key being the previously defined method.
This is displayed as the output on te console.