sethu
sethu

Reputation: 1721

Making multidimensional lists in python

This question maybe asked earlier (atleast topic wise) , but still I couldn't find a solution for my specific problem. Basically, I need a multidimensional array in python. Such that:

I will be able to access contents in list by :

contenets[no_of_record][record]. 

So I have a file like :

101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000011, Gutierrez, Kimberly, 2
101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000013, Mercado, Toby, 1
101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000014, Garcia, Lizzie, 1
101, Mrs. Jones' Math Class, 10100000001, Jones, Barbara, , , , 10100000015, Cruz, Alex, 1

Now I have to maintain a multi dimensional array where no_of_record points to row number and the record will be the column number.

I want something similar to this:

contents=[][]

for lines in source_file:
                contents[no_of_records][]=lines.rstrip().split(',')
                print contents[no_of_records]
                no_of_records+=1

I am sure the snippet above is syntactically wrong, I am just trying to give an idea of what im searching for. Thanks for your help.

-Sethu

Upvotes: 0

Views: 359

Answers (4)

Xavier Combelle
Xavier Combelle

Reputation: 11195

from the csv examples of the doc you should do something along the lines

import csv
rows = []
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row
        rows.append(row)

Upvotes: 4

multipleinterfaces
multipleinterfaces

Reputation: 9163

Use a single list, but populate it further using list objects.

contents = []
for i, line in enumerate(source_file):
    contents.append(line.rstrip().split(','))
    print contents[i]

It looks like you're parsing a csv file, though. I'd suggest using the csv module in stead.

Upvotes: 1

Tom Zych
Tom Zych

Reputation: 13576

You can also do it with dicts, which may be better, if you want to use something other than numbers for the indices.

contents = []
tmp_rcd = {'classnum': 101, 'classname': "Mrs. Jones' Math Class", ...}
contents.append.tmp.rcd
...
print contents[i]['classname']

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 47968

If you really want a list of lists you can do it with this:

contents = [l.split(',') for l in fh] # fh is a file handle here.

There's no good reason not to use the csv module if you're actually working with a csv file though.

Upvotes: 3

Related Questions