1

Task

I have an array with sizes

sizes = [5, 3, 1, 2]

and based on the sizes I want to create the following array

mapping = [0, 0, 0, 0, 0, 1, 1, 1, 2, 3, 3]

Solution

My first attempt

mapping = []
ctr = 0
for i in range(len(sizes)):
    for j in range(sizes[i]):
        mapping.append(i)
        ctr += 1

Shorter version

mapping = [[i for _ in range(sizes[i])] for i in range(len(sizes))]
mapping = list(itertools.chain(*mapping))

Question

One line version?

Is it possible to do it in just one line with a neat code?

2 Answers 2

2

Using enumerate

Ex:

sizes = [5, 3, 1, 2]
result = [i for i, v in enumerate(sizes) for _ in range(v)]
print(result)

Output:

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

Comments

1

Another approach would be to multiply the indices into sublists [[0, 0, 0, 0, 0], [1, 1, 1], [2], [3, 3]] then flatten the result with itertoo.chain.from_iterable:

>>> from itertools import chain
>>> sizes = [5, 3, 1, 2]
>>> list(chain.from_iterable([i] * x for i, x in enumerate(sizes)))
[0, 0, 0, 0, 0, 1, 1, 1, 2, 3, 3]

Comments

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.