Home > Enterprise >  Repeating each element in a list
Repeating each element in a list

Time:04-28

I have two lists:

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y=  [5, 2, 3, 2, 3, 3, 3, 3, 5, 3]

I want to create a new list that contains of multiplies x's first element with the amount of y's first element. That is, I'm looking to produce:

z = [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, ...]

How can I create this list?

CodePudding user response:

One easy way is to use a nested list comprehension with zip:

xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ys = [5, 2, 3, 2, 3, 3, 3, 3, 5, 3]

output = [x for x, y in zip(xs, ys) for _ in range(y)]
print(output)
# [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]

CodePudding user response:

You can use itertools.chain.from_iterable() and itertools.repeat():

list(chain.from_iterable(repeat(elem, count) for elem, count in zip(x, y)))

This outputs:

[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]

CodePudding user response:

You can:

  • Use a list comprehension to create a list of lists of repeated values
  • Use * to unpack the list of lists into iterable arguments (each argument is one of the lists) for itertools.chain() to treat as a single sequence
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [5, 2, 3, 2, 3, 3, 3, 3, 5, 3]

import itertools
z = list(itertools.chain(*[[x[i]] * y[i] for i in range(len(x))]))
print(z)

Output:

[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]

As highlighted by @chepner in a comment, the argument unpacking step using * can be avoided by using chain.from_iterable() instead of chain():

z = list(itertools.chain.from_iterable([[x[i]] * y[i] for i in range(len(x))]))
  • Related