Add the value to a list in corresponding to a number of times that show in another list

Viewed 81

How to simplify and automate the following syntax so that i can achieve:

Assumptions:

  1. lenght of x and y will alway be the same
  2. the number of value in x and y will change

Objective:

  1. print the value in y according to the corresponding number of time that show in x

Expected Output>>> ['a', 'a', 'b', 'b', 'b', 'c']

v = len(x)
x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []

for i in range(x[0]):
    z.append(y[0])
for i in range(x[1]):
    z.append(y[1])
for i in range(x[2]):
    z.append(y[2])

#if there there is forth value being added in both x and y, then it should repeat the step above#

print(z)
6 Answers

Look at using zip() function

z = []
for amount, item in zip(x, y):
  for _ in range(amount):
    z.append(item)

Or, shorter

z = []
for amount, item in zip(x, y):
  z.extend(item for _ in range(amount))

You can use nested loop to do this:

x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []
v = len(x)

for i in range(v):
    for j in range(x[i]):
        z.append(y[i])
print(z)

I'm just letting another possible solution that works.

x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []

for idx in range(len(x)):
    z += list(y[idx] * x[idx])

print(z)
x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []

for i in range(len(x)):
    z.extend([y[i]] * x[i])
        
print(z)

Gives output

['a', 'a', 'b', 'b', 'b', 'c']

this will work fine.

x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []
        
for i in x:
    for o in range(i):
        z.append(y[x.index(i)])
        
 print(z)
Related