Reputation: 107
I have an unusual list sorting problem which I'm struggling to find a concise and efficient way of solving. The problem is as follows: I have a list called indexes with each of the items in this list corresponding to an index for the second list data. So for example the first number in index is zero which corresponds to the first item in the list data which is 1 and the 3 in index corresponds to 6 in the list data because that is the 6 is the 3rd item in the list data [including 0th item]..
Now I want to organise the list data so that that they are grouped between their indexes like below:
indexes = [ 0, 3, 6, 8, 12, 13]
data = [1, 2, 5, 6, 11, 13, 15, 23, 35, 36, 38, 41, 46]
Solution:
organised_data = [ [1,2,5], [6,11,13], [15,23], [35,36,38,41], [46] ]
I've been at this for ages.
Upvotes: 1
Views: 81
Reputation: 369444
Using zip
:
>>> [data[i:j] for i, j in zip(indexes, indexes[1:])]
[[1, 2, 5], [6, 11, 13], [15, 23], [35, 36, 38, 41], [46]]
Upvotes: 2
Reputation: 118011
You can use slicing between consecutive indexes in a list comprehension
>>> [data[indexes[i]:indexes[i+1]] for i in range(len(indexes)-1)]
[[1, 2, 5], [6, 11, 13], [15, 23], [35, 36, 38, 41], [46]]
Upvotes: 5