Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Extract list with difference in extreme values greater than K
When you need to filter sublists based on the range between their minimum and maximum values, you can use list comprehension with the min() and max() functions. This technique is useful for finding sublists with high variability in their elements.
Example
Here's how to extract sublists where the difference between extreme values is greater than K ?
my_list = [[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]]
print("The list is :")
print(my_list)
k = 40
my_result = [element for element in my_list if max(element) - min(element) > k]
print("The result is :")
print(my_result)
The list is : [[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]] The result is : [[13, 52, 11], [94, 12, 21]]
How It Works
Let's break down what happens for each sublist:
my_list = [[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]]
k = 40
for sublist in my_list:
difference = max(sublist) - min(sublist)
print(f"Sublist {sublist}: max={max(sublist)}, min={min(sublist)}, difference={difference}")
print(f"Is difference > {k}? {difference > k}")
print()
Sublist [13, 52, 11]: max=52, min=11, difference=41 Is difference > 40? True Sublist [94, 12, 21]: max=94, min=12, difference=82 Is difference > 40? True Sublist [23, 45, 23]: max=45, min=23, difference=22 Is difference > 40? False Sublist [11, 16, 21]: max=21, min=11, difference=10 Is difference > 40? False
Different K Values
Here's how different K values affect the filtering ?
data = [[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]]
k_values = [20, 40, 80]
for k in k_values:
result = [sublist for sublist in data if max(sublist) - min(sublist) > k]
print(f"K = {k}: {result}")
K = 20: [[13, 52, 11], [94, 12, 21], [23, 45, 23]] K = 40: [[13, 52, 11], [94, 12, 21]] K = 80: [[94, 12, 21]]
Conclusion
Use list comprehension with max() and min() to filter sublists by their range. This technique helps identify sublists with high variability, useful in data analysis and statistical operations.
Advertisements
