# Creating sublist according countinuous intervals

I have a list of number say

l = [1.25, 2.46, 3.99, 4, 5, 6, 7.12, 8.76 ,9.34, 10.42, 11.5, 12.]

I have a list of real intervals

Cl=[[0, 5),[5, 10),[10, 15)]

How to create sublists of l according to the intervals in Cl ? If I was work in N there will be no difficulties.

edit retag close merge delete

Sort by » oldest newest most voted

I have found a solution, but I wonder if it is the best. As I am not Pierre de Fermat, I will give it

Ac=[[x for x in l if bool(x in cl[j])==True] for j in range(len(Cl))]

more

never ever use == True !!! Here you can just write if x in cl[j]

( 2020-06-18 05:31:33 -0600 )edit

Your solution is a brute force approach which does not take into account that the lists of numbers and intervals are ordered. There are surely better solutions if both lists are large. By the way, note that your syntax for intervals is not valid. Try this:

l = [1.25, 2.46, 3.99, 4, 5, 6, 7.12, 8.76 ,9.34, 10.42, 11.5, 12.]
Cl = [[0, 5], [5, 10], [10, 15]]
[[x for x in l if c[0]<=x<c[1]] for c in Cl]

( 2020-06-18 21:58:29 -0600 )edit

## Stats

Seen: 39 times

Last updated: Jun 18 '20