1

I want to create a 2D numpy array from the cartesian product of two lists.

from itertools import product
b1 = 25
b2 = 40
step = 2
lt1 = range(1,b1+1,step)
lt2 = range(1,b2+1,step)
func(product(lt1,lt2,repeat=1))

I want the function to create a 2D numpy array such that the entries are the tuple pairs.

For example, if lt1 = [2,3] and lt2 = [1,4,7], then the 2D array should be

[ [(2,1), (2,4), (2,7)],
  [(3,1), (3,4), (3,7)] ]

My ultimate aim is to create blocks of fixed size from the array and retrieve values corresponding to the block tuples (from a dictionary of lists with keys as the tuples) and eliminate some blocks.

Any help ?

1 Answer 1

1

I hope I've understood your question right. To create 2D numpy array of tuples of integers you can do:

from itertools import product

lt1 = [2, 3]
lt2 = [1, 4, 7]

arr = np.array([*product(lt1, lt2)], dtype=("i,i")).reshape(len(lt1), len(lt2))
print(arr)

Prints:

[[(2, 1) (2, 4) (2, 7)]
 [(3, 1) (3, 4) (3, 7)]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.