def split_l(a,b):
it = iter(b)
start, sub = next(it), []
for ele in a:
if ele >= start:
yield sub
sub, start = [], next(it)
sub.append(ele)
yield sub
print(list(split_l(l1,l2)))
[[0, 0.002, 0.3], [0.5, 0.6, 0.9], [1.3], [1.9]]
using kasras input this beats both the accepted answer and the numpy solution:
In [14]: l1 = [0, 0.002, 0.3, 0.5, 0.6, 0.9, 1.3, 1.9]*1000
In [15]: l1.sort()
In [16]: l2 = [0.5, 1.0, 1.5, 2.0]
In [17]: timeit list(partition(l1,l2))
1000 loops, best of 3: 1.53 ms per loop
In [18]: timeit list(split_l(l1,l2))
1000 loops, best of 3: 703 µs per loop
In [19]: timeit np.split(l1,np.searchsorted(l1,l2))
1000 loops, best of 3: 802 µs per loop
In [20]: list(split_l(l1,l2)) == list(partition(l1,l2))
Out[20]: True
Creating a local reference to append knocks even more off:
def split_l(a, b):
it = iter(b)
start, sub = next(it), []
append = sub.append
for ele in a:
if start <= ele:
yield sub
start, sub = next(it), []
append = sub.append
append(ele)
yield sub
Runs in just over the time of the numpy solution:
In [47]: l1.sort()
In [48]: timeit list(split_l(l1,l2))
1000 loops, best of 3: 498 µs per loop
In [49]: timeit list(partition(l1,l2))
1000 loops, best of 3: 1.73 ms per loop
In [50]: timeit np.split(l1,np.searchsorted(l1,l2))
1000 loops, best of 3: 812 µs per loop