How to remove all sublists outside a given range in a list of lists with Python

1 Answer

0 votes
def remove_sublists_range(lstlst, lower, upper):
    filtered_lst = [sublist for sublist in lstlst if min(sublist) >= lower and max(sublist) <= upper]
     
    return filtered_lst
 
list_of_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
lower_bound = 2
upper_bound = 7


'''
[1, 2, 3]
min = 1 → 1 < 2 fails
Not kept

[4, 5, 6]
min = 4 → 4 ≥ 2 OK
max = 6 → 6 ≤ 7 OK
Kept

[7, 8, 9]
min = 7 → 7 ≥ 2 OK
max = 9 → 9 > 7 fails
Not kept

[10, 11, 12]
min = 10 → 10 > 7 → fails
Not kept
'''

result = remove_sublists_range(list_of_list, lower_bound, upper_bound)
print(result)


 
'''
run:
 
[[4, 5, 6]]
 
'''

 



answered Feb 17 by avibootz
edited Feb 17 by avibootz
...