Your code is almost as fast and fast as it can be. The only slight improvement is to replace [foo(window) for window in row]with map(foo, row), which can be seen from the standards:
> python -m timeit "foo = lambda x: x+1; list(map(foo, range(1000)))"
10000 loops, best of 3: 132 usec per loop
> python -m timeit "foo = lambda x: x+1; [foo(a) for a in range(1000)]"
10000 loops, best of 3: 140 usec per loop
isinstance()It already seems faster than its counterparts hasattr()and type() ==:
> python -m timeit "[isinstance(i, int) for i in range(1000)]"
10000 loops, best of 3: 117 usec per loop
> python -m timeit "[hasattr(i, '__iter__') for i in range(1000)]"
1000 loops, best of 3: 470 usec per loop
> python -m timeit "[type(i) == int for i in range(1000)]"
10000 loops, best of 3: 130 usec per loop
However, if you think that short as neat, you can also simplify your code (after replacing map) with:
mean = lambda x: sum(x)/float(len(x))
output = [foo(r) if isinstance(r, int) else mean(map(foo, r)) for r in data]
source
share