Python – Sort by range inclusion



When it is required to sort the list based on range, the ‘abs’ method, the ‘sum’ method and the list comprehension are used using a function.

Below is a demonstration of the same −

Example

 Live Demo

def sum_range_incl(my_row):    return sum([abs(element [1] - element [0]) for element in my_row if element [0] > i and element [0] < j and element [1] > i and element [1] < j]) my_list = [[(12, 4), (55, 10), (11, 16)], [(42, 14)], [(2, 5), (2, 28), (9, 16)], [(12, 6), (6, 13)]] print("The list is :") print(my_list) i, j = 2, 15 my_list.sort(key=sum_range_incl) print("The resultant list is :") print(my_list)

Output

The list is : [[(12, 4), (55, 10), (11, 16)], [(42, 14)], [(2, 5), (2, 28), (9, 16)], [(12, 6), (6, 13)]] The resultant list is : [[(42, 14)], [(2, 5), (2, 28), (9, 16)], [(12, 4), (55, 10), (11, 16)], [(12, 6), (6, 13)]]

Explanation

  • A method named ‘sum_range_incl’ is defined that takes a list of tuple as a parameter.

  • The list is iterated over using list comprehension.

  • The absolute difference between first and zeroth element is determined for all elements in the list, and the zeroth element is compared to specific integers.

  • The sum of this value is returned as output of the function.

  • A list of list of tuple is defined and is displayed on the console.

  • The values for two integers ‘I’ and ‘j’ are defined.

  • The list is sorted using the sort method by passing the previously defined method as the parameter.

  • The output is displayed on the console.

Updated on: 2021-09-04T10:57:59+05:30

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements