I have one array like A = [1,2,3]
and another array B = [4,5,6]
. Now, I need another array C so that the elements in C should be the same elements of B having occurrence in the order of element A. Like,
C = [4, 5, 5, 6, 6, 6]
In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function.
A = [1,2,3]
B = [4,5,6]
C = [b_item for a_item, b_item in zip(A,B) for _ in range(a_item)]
print C
Result:
[4, 5, 5, 6, 6, 6]
This is a one-line equivalent to:
C = []
for a_item, b_item in zip(A,B):
for _ in range(a_item):
C.append(b_item)
... Which is roughly equivalent to
C = []
for i in range(min(len(A), len(B))):
a_item = A[i]
b_item = B[i]
for _ in range(a_item):
C.append(b_item)
(N.B. Don't get tripped up by the underscore. It's an ordinary variable. It is conventionally used when you don't actually have to refer to the variable's value, as in this example)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With