[Numpy-discussion] list dtype?

David Goldsmith d_l_goldsmith at yahoo.com
Sun Jul 19 18:50:15 EDT 2009


Robert'll correct me if I'm wrong, but I think what he meant is that all you have to do is:

array_of_lists = numpy.empty(<shape tuple>, dtype=object)

and you'll be able to fill array_of_lists with whatever you want:

>>> aol = np.empty((2,2),dtype=object)
>>> aol[:,:] = [[[1, 2, 3], ['a','b','c']], [[(), (), ()], [{}, {}, {}]]]
>>> aol
array([[[1, 2, 3], ['a', 'b', 'c']],
       [[(), (), ()], [{}, {}, {}]]], dtype=object)

However, you do have to specify the shape ahead of time:

>>> aol = np.empty((),dtype=object)
>>> aol[:,:] = [list([5, 6, 7]),list(['a', 'b', 'c'])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: 0-d arrays can't be indexed.
>>> aol.shape = (2,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: total size of new array must be unchanged

(Of course, if you need to change its size and shape, you can always instantiate a new array, initializing the "old" portion of it w/ the existing array and filling in the rest w/ the new values.)

DG

--- On Sun, 7/19/09, Mark Wendell <mark.wendell at gmail.com> wrote:

> From: Mark Wendell <mark.wendell at gmail.com>
> Subject: Re: [Numpy-discussion] list dtype?
> To: "Discussion of Numerical Python" <numpy-discussion at scipy.org>
> Date: Sunday, July 19, 2009, 3:19 PM
> Sorry for being a newbie about it,
> but could you provide an example?
> 
> I was able to do this:
> 
> d = np.dtype( {'names':['mylist'], 'formats':[np.object]})
> but I'm not sure if that's the correct way to produce a
> python list-type dtype.
> 
> Further, how do I then define a new array with that as a
> dtype?
> 
> When I do this:
> a = np.array( (5,5), dtype = d)
> I get the error:
> ValueError: size of tuple must match number of fields.
> 
> 
> Any help appreciated. Thanks!
> Mark
> 
> On Sun, Jul 19, 2009 at 2:37 PM, Robert Kern<robert.kern at gmail.com>
> wrote:
> > On Sun, Jul 19, 2009 at 11:22, Mark Wendell<mark.wendell at gmail.com>
> wrote:
> >> Is it possible to create a dtype that is a list of
> arbitrary length?
> >
> > Use the object dtype.
> >
> > --
> > Robert Kern
> >
> > "I have come to believe that the whole world is an
> enigma, a harmless
> > enigma that is made terrible by our own mad attempt to
> interpret it as
> > though it had an underlying truth."
> >  -- Umberto Eco
> > _______________________________________________
> > NumPy-Discussion mailing list
> > NumPy-Discussion at scipy.org
> > http://mail.scipy.org/mailman/listinfo/numpy-discussion
> >
> 
> 
> 
> -- 
> --
> Mark Wendell
> "I guess songs are just interesting things to do with the
> air." Tom Waits
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> 


      



More information about the NumPy-Discussion mailing list