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.

Example

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[0] - sub[1])))

print("The resultant list is :")
print(my_result)

Output

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)]

Explanation

  • 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.

Updated on: 16-Sep-2021

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements