R function rep() in Python (replicates elements of a list/vector)

后端 未结 8 1778
无人共我
无人共我 2021-01-31 14:20

The R function rep() replicates each element of a vector:

> rep(c(\"A\",\"B\"), times=2)
[1] \"A\" \"B\" \"A\" \"B\"

This is like the list m

8条回答
  •  礼貌的吻别
    2021-01-31 14:43

    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.

提交回复
热议问题