- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 tuples by frequency of their absolute difference
When it is required to sort tuples by frequency of their absolute difference, the lambda function, the ‘abs’ method and the ‘sorted’ method are used.
Below is a demonstration of the same
my_list = [(11, 26), (21, 33), (90, 11), (26, 21), (32, 18), (25, 37)] print("The list is :") print(my_list) my_diff_list = [abs(x - y) for x, y in my_list] my_result = sorted(my_list, key = lambda sub: my_diff_list.count(abs(sub - sub))) print("The resultant list is :") print(my_result)
The list is : [(11, 26), (21, 33), (90, 11), (26, 21), (32, 18), (25, 37)] The resultant list is : [(11, 26), (90, 11), (26, 21), (32, 18), (21, 33), (25, 37)]
A list of tuples is defined and is displayed on the console.
A list comprehension is used to iterate over the list and get the absolute difference between the consecutive elements.
This is converted to a list and stored in a variable.
The ‘sorted’ method is again used on the elements of the list, and the key is specified as ‘lambda’ and the count of the absolute difference between consecutive elements is determined.
This is assigned to a variable and is displayed on the console.
- Python program to Sort Tuples by their Maximum element
- Python program to sort a list of tuples by second Item
- Python program to sort tuples in increasing order by any key.
- Program to sort array by increasing frequency of elements in Python
- Program to update list items by their absolute values in Python
- Python – Sort Tuples by Total digits
- Python program to sort a list of tuples alphabetically
- Python - Restrict Tuples by frequency of first element’s value
- Python – Sort by Uppercase Frequency
- Sort Tuples in Increasing Order by any key in Python program
- Sort Tuples by Total digits in Python
- Python - Sort rows by Frequency of K
- Sort list of tuples by specific ordering in Python
- Python – Sort Matrix by None frequency
- Python program to Sort a List of Dictionaries by the Sum of their Values