Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One liner function to spread python index list

I need a single line function to the following function:

Input =  [1, 3, 7, 9]
Output = [1,1,3,3,7,7,7,7,9,9]

The input string presents the indexes till which the index itself will appear.

So 1 will appear till 1st index (0th and 1st index in output)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

3 will appear till 3rd index after the 1st index (2nd, 3rd index in output)

7 will appear till the 7th index after 3rd index (4th, 5th, 6th, and 7th index in output)

and so on till the last index…

What I thought I can do is the following:

count = 0
Output = []
for i in range(Input[-1]):
  Output.append(Input[count])
  if Input[count] == i:
    count++
return Output

But I feel this should be possible to be written in a single liner or a lambda function or something which looks much cleaner!
Also apologies if the title sounds different than what I am asking. Wasn’t able to find what I needed so linking any helpful answer would be grateful!

>Solution :

Since these are also indices, use each number as start and end limits using zip().

[j for i, j in zip([-1]+Input, Input) for _ in range(i,j)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading