Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating and printing a list in the wrong way

Having the following two list:

sist = ["item1", "item2", "item3"]
numbers = [2,1,4]

I want to print the elements of sist the number of times of the same index of numbers.

This means that in the example posted my desired output is:

item1
item1
item2
item3
item3
item3
item3

This is what I've tried with no success:

for idx in xrange(len(sist)):
    for num in numbers:
        i = 0
        print num
        while i < num:
            print sist[idx]
            i = i + 1 

I think I'm iterating in the wrong way as I'm getting this output:

2
item1
item1
1
item1
4
item1
item1
item1
item1
2
item2
item2
1
item2
4
item2
item2
item2
item2
2
item3
item3
1
item3
4
item3
item3
item3
item3

Can someone please tell me what I'm doing wrong and how to fix it?

like image 764
Avión Avatar asked Nov 29 '25 00:11

Avión


1 Answers

If you would like to use nested for loops like this, you could do

for item, rep in zip(sist, numbers):
    for _ in range(rep):
        print(item)

Output

item1
item1
item2
item3
item3
item3
item3
like image 181
Cory Kramer Avatar answered Nov 30 '25 14:11

Cory Kramer



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!