0

I have this array:

            countOverlaps = [numA, numB, numC, numD, numE, numF, numG, numH, numI, numJ, numK, numL]

and then I condense this array by getting rid of all 0 values:

            countOverlaps = [x for x in countOverlaps if x != 0]

When I do this, I get an output like this: [2, 1, 3, 2, 3, 1, 1]

Which is what it should, so that makes sense. Now I want to add values to the array so that each number adds itself to the array the number of times it appears.

Like this:

Original: [2, 1, 3, 2, 3, 1, 1]

What I want: [2,2,1,3,3,3,2,2,3,3,3,1,1]

Is something like this possible in python?

Thanks

2
  • 2
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem individually. A good way to show this effort is to include a Minimal, complete, verifiable example. Check the intro tour you finished before posting, especially How to Ask. Commented Oct 19, 2018 at 1:15
  • It sounds like you are trying to count the number of times a thing occurs. If so, do you really want to append the number of occurrences to a list? Seems a dictionary would be more appropriate. If so, your output would be this {1: 3, 2: 2, 3: 2} Commented Oct 19, 2018 at 1:19

2 Answers 2

1

Updated

Please check below:

>>> a = [2, 1, 3, 2, 3, 1, 1]
>>> [b for b in a for _ in range(b)]
[2, 2, 1, 3, 3, 3, 2, 2, 3, 3, 3, 1, 1]
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly! Thank you so much
This could be rewritten like [k for k in a for _ in range(k)]
0

This can be done using list comprehension. So far you had:

countOverlaps = [10,25,11,0,10,6,9,0,12,6,0,6,6,11,18]
countOverlaps = [x for x in countOverlaps if x != 0]

This gives us all non=0 numbers. Then we can do what you want with the following code:

mylist = [number for number in list(set(countOverlaps)) for i in range(0, countOverlaps.count(number)) ]

This turns 'mylist' into the following output, which is what you're after:

[6, 6, 6, 6, 9, 10, 10, 11, 11, 12, 18, 25]

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.