daiyue daiyue - 29 days ago 7
Python Question

duplicate each element in a list arbitrary of times

I am wondering how to duplicate each element in a list arbitrary of times, e.g.

l = ['a', 'b', 'c']


the duplicate elements in
l
result in a new list,

n = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c']


so 'a' has been duplicated 3 times, 'b' once, 'c' twice. The number of duplicates for each element are decided by
numpy.random.poisson
e.g.
numpy.random.poisson(2)
.

Answer

Here's a NumPy based vectorized approach using np.repeat to create an array -

np.repeat(l, np.random.poisson([2]*len(l)))

If you need a list as output, append .tolist() there -

np.repeat(l, np.random.poisson([2]*len(l))).tolist()

If you would like to keep at least one entry for each element, add a clipping there with np.random.poisson([2]*len(arr)).clip(min=1).

Comments