Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate an amount of numbers based on a list of numbers in python? [duplicate]

Tags:

python

How do I create a list of following numbers, based on list1?

list1=[2,1,3]

For example:

list1=[2,1,3]

I want to print:

[1, 1, 2, 3, 3, 3] 
 (2)  (1)   (3) #<-- Ignore this part, I just put it to give you more detail of my question

Above, I want to print two (1's), one(2) and three(3's) because list1 = [2,1,3]

Is there any efficient way I can do this in python3? (- Sorry I'm new to Stack Overflow, so please excuse my lack of effective questioning)

like image 229
mickey333 Avatar asked Oct 17 '25 20:10

mickey333


2 Answers

Here is one way of doing this:

list1=[2,1,3]
list2 = []
for j, num in enumerate(list1, 1):
    for _ in range(num):
        list2.append(j)

print(list2)

Output:

[1, 1, 2, 3, 3, 3]
like image 70
Shaheer Avatar answered Oct 20 '25 10:10

Shaheer


You can use enumerate():

n = [2, 1, 3]
result = []
for i, j in enumerate(n, start=1):
    result.extend([i] * j)
like image 41
Alec Avatar answered Oct 20 '25 11:10

Alec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!