1

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!

llllllllll
  • 16,169
  • 4
  • 31
  • 54
Jellyse
  • 839
  • 7
  • 22

3 Answers3

3

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])
llllllllll
  • 16,169
  • 4
  • 31
  • 54
1

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.

Guybrush
  • 2,680
  • 1
  • 10
  • 17
1

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145