Repeat different elements of an array different amounts of times

南笙酒味 提交于 2019-12-02 12:45:09

问题


Say I have an array with longitudes, lonPorts

lonPort =np.loadtxt('LongPorts.txt',delimiter=',')

for example:

lonPort=[0,1,2,3,...]

And I want to repeat each element a different amount of times. How do I do this? This is what I tried:

Repeat =[5, 3, 2, 3,...]

lonPort1=[]

for i in range (0,len(lenDates)):
   lonPort1[sum(Repeat[0:i])]=np.tile(lonPort[i],Repeat[i])

So the result would be:

lonPort1=[0,0,0,0,0,1,1,1,2,2,3,3,3,...]

The error I get is:

list assignment index out of range

How do I get rid of the error and make my array? Thank you!


回答1:


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])



回答2:


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.




回答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.



来源:https://stackoverflow.com/questions/49753980/repeat-different-elements-of-an-array-different-amounts-of-times

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