Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi dimensional arrays in Python of a dynamic size

very new to python so attempting to wrap my head around multi dimensional arrays. I read the existing posts and most of them deal with multi dimensional arrays given dimensions. In my case, I do not have dimensions for the total number of rows possible. A file is being processed, which is CSV and has 7 columns, but each line, depending on meeting or failing a criteria is accordingly drafted into an array. Essentially each line has 7 columns, but the number of rows cannot be predicted. The line is being treated as a list.

My aim is to create a multidimensional array of eligible lines and then be able to access values in the array. how can I do this?

essentially, how do I tackle creating a 2D list:

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

The above creates an mxn sized list but in my case, I know only n (columns) and not m(rows)

like image 962
user1020069 Avatar asked Aug 13 '12 19:08

user1020069


4 Answers

try below

#beg 

a=[[]]

r=int(input("how many rows "))
c=int(input("how many cols "))

for i in range(r-1):
    a.append([])

for i in range(r):
    print("Enter elements for row ",i+1)
    for j in range(c):
        num=int(input("Enter element "))
        a[i].append(num)

for i in range(len(a)):
     print()
     for j in range(len(a[i])):
         print(a[i][j],end="  ")

end

like image 73
Nageswar Rao Mandru Avatar answered Oct 24 '22 06:10

Nageswar Rao Mandru


Nest lists in lists you don't need to predefine the length of a list to use it and you can append on to it. Want another dimension simply append another list to the inner most list.

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

and to use them easily just look at Nested List Comprehensions

like image 8
VoronoiPotato Avatar answered Nov 09 '22 01:11

VoronoiPotato


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

an example of reading lines to a file could be this:

file_name = "/path/to/file"
list = []

with open(file_name) as file:
  file.readline
  if criteria:
    list.append(line)

For multidimensional lists. create the inner lists in a function on and return it to the append line. like so:

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

exchange the last row in the first code with

list.append(returns_list(line))
like image 3
Pablo Jomer Avatar answered Nov 09 '22 01:11

Pablo Jomer


I discovered this to create a simple 2D array list that is 8 elements wide and dynamic in the other dimension

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

Then you can assign any number of variables to the 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]

and so on.....

like image 3
Pete Avatar answered Nov 09 '22 02:11

Pete