R function rep() in Python (replicates elements of a list/vector)
Since you say "array" and mention R. You may want to use numpy arrays anyways, and then use:
import numpy as np
np.repeat(np.array([1,2]), [2,3])
EDIT: Since you mention you want to repeat rows as well, I think you should use numpy. np.repeat
has an axis argument to do this.
Other then that, maybe:
from itertools import izip, chain, repeat
list(chain(*(repeat(a,b) for a, b in izip([1,2], [2,3]))))
As it doesn't make the assumption you have a list or string to multiply. Though I admit, passing everything as argument into chain is maybe not perfect, so writing your own iterator may be better.
Use numpy
arrays and the numpy.repeat function:
import numpy as np
x = np.array(["A", "B"])
print np.repeat(x, [2, 3], axis=0)
['A' 'A' 'B' 'B' 'B']
Not sure if there's a built-in available for this, but you can try something like this:
>>> lis = ["A", "B"]
>>> times = (2, 3)
>>> sum(([x]*y for x,y in zip(lis, times)),[])
['A', 'A', 'B', 'B', 'B']
Note that sum()
runs in quadratic time. So, it's not the recommended way.
>>> from itertools import chain, izip, starmap
>>> from operator import mul
>>> list(chain.from_iterable(starmap(mul, izip(lis, times))))
['A', 'A', 'B', 'B', 'B']
Timing comparions:
>>> lis = ["A", "B"] * 1000
>>> times = (2, 3) * 1000
>>> %timeit list(chain.from_iterable(starmap(mul, izip(lis, times))))
1000 loops, best of 3: 713 µs per loop
>>> %timeit sum(([x]*y for x,y in zip(lis, times)),[])
100 loops, best of 3: 15.4 ms per loop