
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Python program to sort strings by substring range
- Python – Sort by Uppercase Frequency
- Python – Sort Dictionaries by Size
- Sort Array By Parity in Python
- Python – Sort row by K multiples
- Python – Sort Matrix by total characters
- Python – Sort Tuples by Total digits
- Python – Sort Matrix by Row Median
- Python – Sort Matrix by None frequency
- Python – Sort Matrix by Palindrome count
- Python – Sort Strings by Case difference
- Python – Sort Matrix by Maximum String Length
- Python – Sort by Maximum digit in Element
- Python - Sort Matrix by Maximum Row element
- Python – Sort a List by Factor count
