[Python] Repeat function in python similar to R

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a repeat function in python similar to the rep function in R? If not, how to create one?

    R has a powerful rep function as follows:

    rep(x, times = 1, length.out = NA, each = 1)


    • x: a vector


    • times: an integer-valued vector giving the (non-negative) number of times to repeat each element if of length length(x), or to repeat the whole vector if of length 1. Negative or NA values are an error. A double vector is accepted, other inputs being coerced to an integer or double vector.


    • length.out: non-negative integer. The desired length of the output vector. Other inputs will be coerced to a double vector and the first element taken. Ignored if NA or invalid.


    • each: non-negative integer. Each element of x is repeated each times. Other inputs will be coerced to an integer or double vector and the first element taken. Treated as 1 if NA or invalid.

    Some examples are as follows:

    R code
    > letters
    [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v"
    [23] "w" "x" "y" "z"
    #Example 1
    > rep(letters[1:3],times=c(1,2,4))
    [1] "a" "b" "b" "c" "c" "c" "c"
    #Example 2
    > rep(letters[1:3],each=2,len=15)
    [1] "a" "a" "b" "b" "c" "c" "a" "a" "b" "b" "c" "c" "a" "a" "b"
    #repeat a:c each element 2 until length be 15
    #Example 3
    > rep(letters[1:3],each=3,times=2)
    [1] "a" "a" "a" "b" "b" "b" "c" "c" "c" "a" "a" "a" "b" "b" "b" "c" "c" "c"
    #repeat a:c each element 3 and repeat this 2 times
    #Example 4
    > rep(letters[c(TRUE,FALSE)],each=2)
    [1] "a" "a" "c" "c" "e" "e" "g" "g" "i" "i" "k" "k" "m" "m" "o" "o" "q" "q" "s" "s" "u" "u"
    [23] "w" "w" "y" "y"
    #Example 5
    > rep(letters[c(TRUE,FALSE,TRUE,FALSE,FALSE)],each=2)
    [1] "a" "a" "c" "c" "f" "f" "h" "h" "k" "k" "m" "m" "p" "p" "r" "r" "u" "u" "w" "w" "z" "z"
    #Example 6
    > rep(letters[c(TRUE,FALSE,TRUE,FALSE,FALSE)],each=2,len=25)
    [1] "a" "a" "c" "c" "f" "f" "h" "h" "k" "k" "m" "m" "p" "p" "r" "r" "u" "u" "w" "w" "z" "z"
    [23] "a" "a" "c"


    As we saw above, the rep function can produce complex sequences. So, is there a function that does the same as R's rep? If not, at least how to create a similar one? The function should handle all of the above examples to check its flexibility!

    Continue reading...

Compartilhe esta Página