Home > Blockchain >  What is the most efficient way to use mesh grid with parameters in python?
What is the most efficient way to use mesh grid with parameters in python?

Time:01-20

def s(x,y,z,t1,t2):
    return x   y   z   t1   t2
        
X = [1,2,3]
Y = [4,5,6]
Z = [7,8,9]
Theta = [(1,2),(3,4),(5,6),(1,1)]

Is there any way for me to efficiently construct an array containing the evaluations of X cross Y cross Z cross Theta with respect to the function s ? Note that I do not want s(1,4,7,1,3), but I do want s(1,4,7,1,2); as in, I don't want s to be evaluated at X cross Y cross Z cross {1,3,5,1} cross {2,4,6,1}.

Thanks.

CodePudding user response:

List comprehension:

results = [s(x, y, z, t1, t2) for x in X
                              for y in Y
                              for z in Z
                              for t1, t2 in Theta]

is the most efficient pure python way of doing this.

CodePudding user response:

Can you write the issue mathematically or provide an example with the expected result?

(My reputation is too low to comment)

CodePudding user response:

X = [1,2,3]
Y = [4,5,6]
Z = [7,8,9]
Theta = [(1,2),(3,4),(5,6),(1,1)]

[(a,b,c,d) for a,b,c,d in zip(X,Y,Z,Theta)]

#[(1, 4, 7, (1, 2)), (2, 5, 8, (3, 4)), (3, 6, 9, (5, 6))]

Or

[(a,b,c,*d) for a,b,c,d in zip(X,Y,Z,Theta)]
#[(1, 4, 7, 1, 2), (2, 5, 8, 3, 4), (3, 6, 9, 5, 6)]

If you want sum:

[sum([a,b,c,*d]) for a,b,c,d in zip(X,Y,Z,Theta)]
#[15, 22, 29]
  • Related