Jellyse
Jellyse

Reputation: 863

Repeat different elements of an array different amounts of times

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!

Upvotes: 1

Views: 219

Answers (3)

timgeb
timgeb

Reputation: 78650

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.

Upvotes: 1

Guybrush
Guybrush

Reputation: 2780

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.

Upvotes: 1

llllllllll
llllllllll

Reputation: 16404

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

Upvotes: 3

Related Questions