Home > Blockchain >  How to make a matrix from two arrays
How to make a matrix from two arrays

Time:09-17

I have two arrays:

import numpy as np

MC=np.array([1, 2, 3])
oo=np.array([4,5,6])

for i in range(0, len(MC)): 
    for j in range(0, len(oo)):
        H[i,j]=(MC[i],oo[j])   

print(oo)    
print(H)

I want an output matrix like this and I get an error: H=[[(1,4),(1,5),(1,6)],[(2,4),(2,5),(2,6)],[(3,4),(3,5),(3,6)]]

CodePudding user response:

"I get an error" is quite unspecific. So you should provide more details. But I assume that you get a NameError since H is not defined anywhere before using it. But looking at you implementation I can't see how you would get the desired result anyway. If you generally don't know the length of the given arrays in advance you could try

H = []
for i in range(0, len(MC)):
    H.append([])
     for j in range(0, len(oo)):
         H[-1].append((MC[i], oo[j]))

That should give you the desired output. Or in my opinion even better, particulary in terms of readability:

H = []
for mc_el in MC:
    H.append([])
     for oo_el in oo:
         H[-1].append((mc_el, oo_el))

Or (inspired by nikoros' answer):

H = [[(MC_el, oo_el) for oo_el in oo] for MC_el in MC]

CodePudding user response:

Instead of manually iterating the arrays, you can combine groupby and product from itertools, you can create the required list of list of tuples in List-Comprehension

>>> from itertools import groupby, product
>>> [list(product([k], oo)) for k,v in groupby(MC)]

[[(1, 4), (1, 5), (1, 6)], [(2, 4), (2, 5), (2, 6)], [(3, 4), (3, 5), (3, 6)]]
  • Related