Multidimensional arrays in Python with dynamic size

very new to python, so we are trying to wrap our head around multidimensional arrays. I read the existing posts, and most of them relate to arrays with several sizes specified by parameters. In my case, I have no sizes for the total number of possible rows. The file is processed, which is a CSV and has 7 columns, but each row, depending on the conformity or absence of criteria, is accordingly converted to an array. Essentially each row has 7 columns, but the number of rows cannot be predicted. The line is considered as a list.

My goal is to create a multidimensional array of matching strings and then access the values ​​in the array. How can i do this?

essentially, how do I decide to create a 2D list:

list_2d = [[foo for i in range(m)] for j in range(n)] 

The above list of sizes is mxn, but in my case I only know n (columns), not m (rows)

+8
source share
5 answers

Put the lists in the lists, you do not need to pre-determine the length of the list in order to use it, and you can add to it. If you want a different dimension, just add another list to the innermost list.

 [[[a1, a2, a3] , [b1, b2, b3] , [c1, c2, c3]], [[d1, d2, d3] , [e1, e2, e3] , [f1, f2, f3]]] 

and use them easily, just look at the understanding of the nested list

+5
source

In python there is no need to declare the size of the list on forehand.

An example of reading lines in a file might be the following:

 file_name = "/path/to/file" list = [] with open(file_name) as file: file.readline if criteria: list.append(line) 

For multidimensional lists. create internal lists in the function and return them to the add line. So:

 def returns_list(line): multi_dim_list = [] #do stuff return multi_dim_list 

exchange the last line in the first code with

 list.append(returns_list(line)) 
+3
source

I am new to python, but I discovered this to create a simple list of 2D arrays that has 8 elements and is dynamic in another dimension

 list2d=[[] for i in xrange(8)] 

Then you can assign any number of variables to an 8-wide array

 list2d[0]=[1,2,3,4,5,6,7,8,9,10,11] list2d[1]=[12,13,14,15,16,17,18,19] 

etc.

I hope this helps

Pete

+2
source

If you are guaranteed the "n" columns, you can transpose in memory.

 from collections import defaultdict import csv cols = defaultdict(list) with open('somefile.csv') as csvin: for row in csv.reader(csvin): for colno, col in enumerate(row): cols[colno].append(col) 

Still not 100% sure this is your question, though ...

0
source

You can even try this, I succeeded

s = [[] for y in range(n)]

0
source

All Articles