Multi dimensions list. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Multi dimensions list. (/thread-13245.html) |
Multi dimensions list. - voidptr - Oct-06-2018 hi from a noob 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 * 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])]) else: for x in range(ijk[0]): mx = [] m.append(mx) mdo(mx, ijk[1:]) m = [] mdo(m,dims) return(m) #----------------- m = mtxNew(2,3,4,5) m[1][2][3][4] = 666 RE: Multi dimensions list. - Gribouillis - Oct-06-2018 Hello voidptr, you can do this directly with the numpy.ndarray typeimport numpy as np a = np.zeros(shape=(2,3,4,5), dtype=int) a[1][2][3][4] = 666If 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() RE: Multi dimensions list. - voidptr - Oct-07-2018 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 |