[Numpy-discussion] how to use the name of a ndarray as a string

Olivier Delalleau shish@keba...
Thu Nov 10 05:57:25 CST 2011


In such a situation you should probably use a dictionary from the start,
i.e.:
   d3['index'] = np.arange(100)
then use d3['index'] everywhere instead of index.

It can be more convenient (notation-wise) to use an object instead, i.e.
either work within a class method (self.index = np.arange(100)), or use a
class as storage instead of a dictionary:

class ArrayHolder(object):
    pass

a = ArrayHolder()

a.index = np.arange(100)
...
d3 = a.__dict__.copy()

Finally, another option I can see is to use a custom class that holds both
a numpy array and a name. Maybe with a convenient accessor to the array
through the call method:

class NamedArray(object):

    def __init__(self, array, name):
        self.array = array
        self.name = name

    def __call__(self):
        return self.array

index = NamedArray(numpy.arange(100), 'index')
...   # use index() in the rest of the code whenever you want the numpy
array
d3[index.name] = index()

-=- Olivier

2011/11/10 Chao YUE <chaoyuejoy@gmail.com>

> Hi,
>
> Does anyone know how I can quickly use the name of a ndarray as a string?
> for example, I have
> In [54]: index=np.arange(100)
>
> then I want to use the name 'index' as a key in a new dictionary:
> d3=dict()
> d3['index']=index
>
> I can do it like the way above, but I have many ndarray variables that
> need to be included in the dictionary.
> is there something like:
> d3[index.name()]=index
> while index.name() would equal the string 'index'?
>
> I hope my question is clear. thanks to all.
>
> Chao
> --
>
> ***********************************************************************************
> Chao YUE
> Laboratoire des Sciences du Climat et de l'Environnement (LSCE-IPSL)
> UMR 1572 CEA-CNRS-UVSQ
> Batiment 712 - Pe 119
> 91191 GIF Sur YVETTE Cedex
> Tel: (33) 01 69 08 29 02; Fax:01.69.08.77.16
>
> ************************************************************************************
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20111110/94482375/attachment.html 


More information about the NumPy-Discussion mailing list