Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get one number specific times in an array python

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]

like image 759
sparrow Avatar asked May 20 '15 19:05

sparrow


People also ask

How do you repeat a value in an array in Python?

In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function.


1 Answers

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)

like image 80
Kevin Avatar answered Sep 28 '22 16:09

Kevin