I have two lists, one containing some unique elements (integers in my case) and the other containing indices that indicate into which sublist of a newly created nested list the elements should be inserted.
elements = [1, 2, 3, 4, 5, 6]
indices = [0, 0, 1, 2, 2, 1]
expected_result = [[1, 2], [3, 6], [4, 5]]
The list of elements contains only unique items, potentially not sorted. The list of indices is 'normalized' such that the lower indices will always occur first. The new nested list should use the indices to determine the sublist of the expected result to which the elements shall belong.
I have come up with the following function, but I have a feeling that there should be an easier way.
def indices_to_nested_lists(indices: Sequence[int], elements: Sequence):
result = []
for i in range(max(indices)+1):
sublist = []
for j in range(len(elements)):
if indices[j] == i:
sublist.append(elements[j])
result.append(sublist)
return result
Can anyone think of an easier, maybe more pythonic way of achieving the same result?