Bottom Page

Thread Rating:
• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 Multi dimensions list. voidptr Programmer named Tim Posts: 13 Threads: 4 Joined: Oct 2018 Reputation: 2 Likes received: 0 #1 Oct-06-2018, 06:58 AM 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 ``` Gribouillis Posts: 2,586 Threads: 31 Joined: Jan 2018 Reputation: 246 Likes received: 606 #2 Oct-06-2018, 09:59 AM (This post was last modified: Oct-06-2018, 09:59 AM by Gribouillis. Edited 2 times in total.) 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() ``` voidptr Programmer named Tim Posts: 13 Threads: 4 Joined: Oct 2018 Reputation: 2 Likes received: 0 #3 Oct-07-2018, 04:54 PM 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 « Next Oldest | Next Newest »

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)