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

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

    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
    

提交回复
热议问题