Deivid
Deivid

Reputation: 57

Repeat list elements based in another list

I would like to repeat elements from one list based in a second list, like this:

i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for x in j:
    while i <= x:
        print(x)
        i += 1

I've got this result:

1
1
4
4
4
10
10
10
10
10
10

I'd like to get this result:

11.65
11.65
11.69
11.69
11.69
11.71
11.71
11.71
11.71
11.71
11.71

Upvotes: 0

Views: 132

Answers (2)

eroc123
eroc123

Reputation: 640

j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for i in range(len(j)): #assuming the lenth of both list is always the same
    for k in range(j[i]):
        print(z[i])

Do you mean something like this?

there is a 1, 4, and 10

so print the first item in z 1 time, second item 4 times and the third 10 times?

Upvotes: 0

azro
azro

Reputation: 54148

You may iterate on both list together, using zip, then increase i until you reach the bound of the current value

i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for bound, value in zip(j, z):
    while i <= bound:
        print(value)
        i += 1

Upvotes: 1

Related Questions