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.