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

后端 未结 8 1795
无人共我
无人共我 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:34

    The numpy.repeat has been mentioned, and that's clearly the equivalent to what you want. But for completenes' sake, there's also repeat from the itertools standard library. However, this is intended for iterables in general, so it doesn't allow repetions by index (because iterables in general do not have an index defined).

    We can use the code given there as a rough equivalent

    def repeat(object, times=None):
        # repeat(10, 3) --> 10 10 10
        if times is None:
            while True:
                yield object
        else:
            for i in xrange(times):
                yield object
    

    to define our own generalised repeat:

    def repeat_generalised(object, times=None):
        # repeat(10, 3) --> 10 10 10
        if times is None:
            while True:
                yield object
        else:
            for reps, elem in zip(times, object):
                for i in xrange(reps): 
                    yield elem
    

    The problem of course is that there's a lot of possible edge cases you have to define (What should happen if object and times have a different number of elements?), and that would depend on you individual use case.

提交回复
热议问题