Repeat each values of an array different times

前端 未结 2 1326
一生所求
一生所求 2020-11-28 16:19

Suppose a = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] and s = [3, 3, 9, 3, 6, 3]. I\'m looking for the best way to repeat a[i] exactly s[i]

相关标签:
2条回答
  • 2020-11-28 16:53

    That's exactly what numpy.repeat does:

    >>> a = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
    >>> s = np.array([3, 3, 9, 3, 6, 3])
    >>> np.repeat(a, s)
    array([ 0.1,  0.1,  0.1,  0.2,  0.2,  0.2,  0.3,  0.3,  0.3,  0.3,  0.3,
            0.3,  0.3,  0.3,  0.3,  0.4,  0.4,  0.4,  0.5,  0.5,  0.5,  0.5,
            0.5,  0.5,  0.6,  0.6,  0.6])
    

    In pure Python you can do something like:

    >>> from itertools import repeat, chain, imap
    >>> list(chain.from_iterable(imap(repeat, a, s)))
    [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.6, 0.6, 0.6]
    

    But of course it is going to be way slower than its NumPy equivalent:

    >>> s = [3, 3, 9, 3, 6, 3]*1000
    >>> a = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]*1000
    >>> %timeit list(chain.from_iterable(imap(repeat, a, s)))
    1000 loops, best of 3: 1.21 ms per loop
    >>> %timeit np.repeat(a_a, s_a) #a_a and s_a are NumPy arrays of same size as a and b
    10000 loops, best of 3: 202 µs per loop
    
    0 讨论(0)
  • 2020-11-28 16:57

    Here's a one-liner using only (nested) list comprehensions:

    [item for z in [[x]*y for (x,y) in zip(a, s)] for item in z]
    
    0 讨论(0)
提交回复
热议问题