I have two lists: l1 = [0, 0.002, 0.3, 0.5, 0.6, 0.9, 1.3, 1.9]
and l2 = [0.5, 1.0, 1.5, 2.0]
. I want to split l1
in to sublists that are defined as the elements between two indexes of l2
. So for example l1
would be equal to [[0,0.002, 0.3], [0.5, 0.6, 0.9], [1.3], [1.9]]
.
Here is my solution:
l3 = []
b=0
for i in l2:
temp = []
for p in l1:
if b <= p < i:
temp.append(p)
l3.append(temp)
b+=0.5
This solution is a huge bottleneck in my code. Is there a faster way to do this?
Your lists are sorted, so there is no need to do a double loop here.
The following generates the sublists based on the two lists as inputs:
def partition(values, indices):
idx = 0
for index in indices:
sublist = []
while idx < len(values) and values[idx] < index:
sublist.append(values[idx])
idx += 1
if sublist:
yield sublist
You can then iterate over partition(l1, l2)
to get individual sublists, or call list()
to produce the whole list-of-lists in one go:
>>> l1 = [0, 0.002, 0.3, 0.5, 0.6, 0.9, 1.3, 1.9]
>>> l2 = [0.5, 1.0, 1.5, 2.0]
>>> list(partition(l1, l2))
[[0, 0.002, 0.3], [0.5, 0.6, 0.9], [1.3], [1.9]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With