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
Solution 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])
Solution 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 -= 1for value in repeat_items(x, repeat):
print(value, end=' ')
displays 0 0 0 0 1 1 1 2 2 3
.
Solution 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 inzip(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.
Post a Comment for "Repeat Different Elements Of An Array Different Amounts Of Times"