Repeat different elements of an array different amounts of times

不羁的心 提交于 2019-12-02 05:48:27

You can use np.repeat():

np.repeat(a, [5,3,2,3])

Example:

In [3]: a = np.array([0,1,2,3])

In [4]: np.repeat(a, [5,3,2,3])
Out[4]: array([0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3])

Without relying on numpy, you can create a generator that will consume your items one by one, and repeat them the desired amount of time.

x = [0, 1, 2, 3]
repeat = [4, 3, 2, 1]

def repeat_items(x, repeat):
  for item, r in zip(x, repeat):
    while r > 0:
      yield item
      r -= 1


for value in repeat_items(x, repeat):
  print(value, end=' ')

displays 0 0 0 0 1 1 1 2 2 3.

Providing a numpy-free solution for future readers that might want to use lists.

>>> lst = [0,1,2,3]
>>> repeat = [5, 3, 2, 3]
>>> [x for sub in ([x]*y for x,y in zip(lst, repeat)) for x in sub]
[0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3]

If lst contains mutable objects, be aware of the pitfalls of sequence multiplication for sequences holding mutable elements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!