Reputation: 66
I am trying to pass in varying number of function arguments into a function. Specifically, I am trying create a meshgrid using numpy.meshgrid, with variable number of inputs: i.e. n-dimensional grid that is determined by user input.
I have a collection of arrays to produce the grid within a dictionary. The keys being the indices, and the items of the dictionaries being an array containing the points that I wish to make the grid from.
Right now, I feel that I can do it with a for loop somehow like this:
dict= {'v1':np.array([1,2,3,4,5]), 'v2':np.array([5,6,7,8,9])}
grid = np.array(np.meshgrid(for keys in dict.keys: dict[keys]))
In other words, the number of arguments I wish to pass on to numpy.meshgrid are dependent on the number of keys in my dictionary, and I want to pass on the corresponding list I have stored as items in my dictionary. Is there any way I can do this?
Upvotes: 0
Views: 894
Reputation: 1663
This might be what you want
import numpy as np
dict= {'v1':np.array([1,2,3,4,5]), 'v2':np.array([5,6,7,8,9])}
def give_me_grid(d):
return np.array(np.meshgrid(*(v for _, v in sorted(d.items()))))
print(give_me_grid(dict))
Upvotes: 1