Numeric N-dimensional array initialization

Robert Kern robert.kern at gmail.com
Thu Jun 22 14:25:11 EDT 2006


TG wrote:
> Hi there !
> 
> I'm just starting to use Numeric here, and I'm wondering : how can I
> efficiently initialize every values of a N-dimensional array, given I
> don't know the number of dimensions ?
> 
> I'm looking for something like a map function, or a way to conveniently
> iterate through the whole N-array, but I didn't find anything ... yet.
> If anyone has a clue, I'm listening.

Since you're just starting, you should know that Numeric is no longer being 
developed. The actively developed version is numpy:

   http://www.scipy.org/NumPy

You will want to ask numpy questions on the numpy-discussion mailing list. The 
answers one gets here tend to be hit or miss.

   https://lists.sourceforge.net/lists/listinfo/numpy-discussion

As to your actual question, I'm not entirely sure what you are asking for, but 
you should look at the .flat attribute.


In [5]: from numpy import *

In [6]: a = empty((2, 3))

In [7]: a.flat[:] = 10

In [8]: a
Out[8]:
array([[10, 10, 10],
        [10, 10, 10]])

# Note, in numpy, .flat is not a real array although it should be usable in most
# places that need an array. However, unlike Numeric, it can  always be used
# even if the array is not contiguous. If you need a real array, use the
# .ravel() method, but know that it will make a copy if the array is not
# contiguous (for example, if it is the result of a .transpose() call).
In [9]: a.flat
Out[9]: <numpy.flatiter object at 0x196a800>

In [10]: a.flat = arange(10)

In [11]: a
Out[11]:
array([[0, 1, 2],
        [3, 4, 5]])

In [12]: for i in a.flat:
    ....:     print i
    ....:
    ....:
0
1
2
3
4
5

-- 
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




More information about the Python-list mailing list