3

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?

1 Answer 1

2

Try using this for loop with zip:

l = [[] for i in range(max(indices) + 1)]
for x, y in zip(elements, indices):
    l[y].append(x)
print(l)

Output:

[[1, 2], [3, 6], [4, 5]]
Sign up to request clarification or add additional context in comments.

3 Comments

TypeError: can only concatenate list (not "int") to list. I get an error
It's just a typo — it should be l = [[] for i in range(max(indices) + 1)]. It's a great answer. You could also write that line as l = [[]] * (max(indices) + 1).
Ah, yes so much nicer! Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.