[SciPy-user] ragged arrays

David Grant david.grant at telus.net
Sun Jun 4 18:39:29 EDT 2006


On Sunday 04 June 2006 14:51, John Hunter wrote:
> >>>>> "David" == David Grant <david.grant at telus.net> writes:
>
>     David> Simple question, in Matlab you can do ragged arrays using
>     David> "cell arrays." Is the equivalent thing in
>     David> scipy/numpy/python just a List of arrays? I made one here:
>
>     David> In [55]:a Out[55]: [array([0, 0, 0, 0, 0]), array([0, 0, 0,
>     David> 0, 0, 0]), array([0, 0, 0, 0]), array([1, 1, 1, 1])]
>
> Oh man, that brings back a dreadful past -- cell arrays.  The built-in
> python data structures are much richer.  You can use a list or a
> dictionary to store them, or a class that derives from one of these or
> a custom class.
>
> One good solution is to derive a custom class from list with helper
> methods to operate over the list of arrays.  Eg, if you needed to find
> the max element over all of your ragged arrays, you could do something
> like
>
> class ragged(list):
>     def max(self):
>         return max([max(x) for x in self])
>
> import numpy as n
> n1 = n.rand(10)
> n2 = n.rand(20)
> n3 = n.rand(30)
>
> r = ragged((n1, n2, n3))
> print r.max()
>
> n4 = n.rand(12)
> r.append(n4)
> print r.max()

That is really cool. Thanks. I was going to do the exact same thing except I 
was just going to implement max as a static method that operated on a list. 
This is much better. And using the list comprehension thing makes it so 
compact as well.

Dave




More information about the SciPy-User mailing list