Marc
Marc

Reputation: 1

Getting an entry in a List of lists in python

I have a large .txt file of data. I am having trouble getting just a single line of data from the lists of lists. Instead I am getting the column instead of an entry.

here is the sample data set I have been working with...

['6/1/13', '9852', '54946', '47498.85', '220999.39', '26752', '2165', '0', '0']

['6/2/13', '17590', '72536', '70659.35', '291658.75', '28248', '4723', '4723', '289']

['6/3/13', '8599', '81135', '31547.41', '323206.16', '29611', '1160', '1160', '221']

['6/4/13', '17589', '98724', '106170.69', '429376.85', '31090', '2922', '2922', '394']

Below is the code I have been attempting with...

file = open("blahblah.txt","r")
data = []
for line in file:
    parts = line.strip().split()
    data.append(parts)
    print parts [0]

Below is the output that I get when i input this code.

6/1/13

6/2/13

6/3/13

6/4/13

When i ask for it to print parts[0] shouldn't it give just the first line of the list of lists? instead it gives me the entry in the first column of the 4 lists. How can I fix my code that I just get the first line beginning with ['6/1/13']

Upvotes: 0

Views: 61

Answers (2)

khtad
khtad

Reputation: 1175

If your data is parsable by the csv module, the following code will work:

with open(txtpath, mode='r', newline='') as f:
    fReader = csv.reader(f, delimiter=' ')
    for rows in fReader:
        list0fRows.append(rows)
        print rows

parts[0] is the first entry in the parts list--I think you want data[0] for the first row. The code in this example will print each row in order.

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Look at the below code

for line in file:
    parts = line.strip().split()
    data.append(parts)
    print parts [0]

Firstly, your code should not work. Even if it works, the print parts [0] instruction is executed in every iteration. So you will get first portion of every list.

It is not clear how your file looks like. I assume it is just like your sample data. So the below code works.

import re

file = open("example.txt","r")
data = []
for line in file:
    line=re.sub('[\[\],\'\']', ' ', line)
    llist =line.split()
    data.append(llist)

print data[0][0]

Output:

6/1/13

To get the whole line, change the print statement to print data[0]

Output:

['6/1/13', '9852', '54946', '47498.85', '220999.39', '26752', '2165', '0', '0']

Upvotes: 1

Related Questions