简体   繁体   中英

Python: Expand 2D array to multiple 1D arrays

Consider the followoing example from np.meshgrid docs :

nx, ny = (3, 2)
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
xv, yv = np.meshgrid(x, y)

In my application, instead of x and y , I've 25 variables. To create a grid out of the 25 variables, one way would be:

v1 = np.linspace(0, 1, 10)
v2 = np.linspace(0, 1, 10)
...
v25 = np.linspace(0, 1, 10)

z_grid = np.meshgrid(v1, v2, ..., v25)

However, the code will look ugly and not modular w.r.t. the number of variables (since each variable is hard-coded). Therefore, I am interested in something like the following:

n_variables = 25
z = np.array([np.linspace(0, 1, 10)] * n_variables)
z_grid = np.dstack(np.meshgrid(z))

However, I am guessing meshgrid(z) is not the correct call, and I should expand z to n_variables arrays. Any thoughts on how I can expand the 2D array into multiple 1D arrays?

this should do it.

n_variables = 25
z = np.array([np.linspace(0, 1, 10)] * n_variables)
z_grid = np.dstack(np.meshgrid(*z))

the * operator before list, unpacks list elements. consider following:

v1 = [1,2,3]
v2 = [4,5,6]
list_of_v = [v1,v2]
some_fucntion(v1,v2) == some_function(*list_ov_v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM