Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Multi dimensions list.
hi from a noob Tongue

I needed a way to create multi dimensions list...
Didn't find any in the 'native' python ...
So here my first draft, feel free to comment and post you idea Smile *

Maybe there is a way to subclass List or collections ....

def mtxNew(*dims):
    _defv = 0

    def mdo(m,ijk):
        if len(ijk) == 1:
            m.extend([_defv for x in range(ijk[0])])
            for x in range(ijk[0]):
                mx = []
                mdo(mx, ijk[1:])

    m = []


m = mtxNew(2,3,4,5)
m[1][2][3][4] = 666

Hello voidptr, you can do this directly with the numpy.ndarray type
import numpy as np
a = np.zeros(shape=(2,3,4,5), dtype=int)
a[1][2][3][4] = 666
If you prefer nested python lists, you can write a converter
def listify(a):
    return [x for x in a] if len(a.shape) == 1 else [listify(x) for x in a]
a = listify(np.array(shape=(2,3,4,5), dtype=int))
Ooops! sorry, the converter already exists in numpy with the .tolist() method:
my_nested_list = np.zeros(shape=(2, 3, 4, 5), dtype=int).tolist()
Yes I didn't have numpy install and I wanted a quick way to build matrix...
Long time ago I created a multidimension array package and it is not so easy,
so yes Numpy is the way :o)

It was fun to reinvent the wheel tho and play with python language a bit :0P

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)