a fast function taking either variable or collection as argument
I want to create a function which takes either variable or collection as argument. If the input is any kind of collection, function should be taken of every element in it and return a numpy array of results. Currently, I do in this way:
def simplefunc(x):
<some code here> # it is assumed that x is a single variable
return <some single result>
def arrayfunc(x):
try: #check if we have a collection
x_iterator = iter(x)
except TypeError: #this is a single expression
return simplefunc(x)
else: # iterate through iterable x
ret=[]
for xx in x:
ret.append(simplefunc(xx))
return numpy.array(ret)
It works as is, however, I do not think this is the fastest way possible,especially the method to figure out if the input is a collection. I also do not like that strings are considered as collections and split to chars (I can stand it though). Is there a more elegant way?
I tried also to call arrayfunc() recursively on each element of collection (instead of simplefunc()), to handle collections of collections in the same way, however, it runs into infinite loop on strings. I have to check if the input is a string explicitly.
Perhaps using 'map(function, sequence)' would help? 'try: L = map(simplefunc, x) ...'. See http://docs.python.org/tutorial/datastructures.html#functional-programming-tools
Thanks a lot... this I may have overlooked while googling.. However, this does not work if I have some other non-sequence parameters in my function Maybe better to post this as an answer?
Your function above doesn't have non-sequence parameters, so I'm not sure how you plan to deal with those. You could always make a partial function (look up partial in the functools package). List comprehensions deal nicely with this too.