views:

226

answers:

5

this section of code is supposed to make a list containing the values of the second column in the text file, but it takes the second letter. anyone know what my problem is?

TEXTFILE  
opi 60  
kid 60  
pou 60  
ret 60  
kai 60  
bob 100  

for line in lst:                          
    line.split(' ')  
    fire.append(int(line[1]))
    print(line[1])
A: 
line.split(' ')

Your mistake is there, the split doesn't split line but returns a line split. So instead what you need to do is

columns = line.split(' ')

and use columns instead

hhafez
+1  A: 

You probably want to do something like this:

mylist = []

for line in file:
    firstcolval, secondcolval = line.split()
    mylist.append(int(firstcolval))
ChristopheD
+1  A: 

This should also work

import csv
for line in csv.reader(open("datafile"), delimiter=" "):                          
    fire.append(int(line[1]))
    print(line[1])

Alternatively

from operator import itemgetter
import csv
f=csv.reader(open("datafile"),delimiter=' ')
fire+=[int(x[1]) for x in f]
gnibbler
A: 

You can do it with a simple one liner.

fire = [int(b) for a, b in line.split(" ") for line in lst]
Anand Chitipothu
A: 

Okay, so since split creates a new object (list containing at least one element), you should do:

for line in lst:
    lc = line.split(' ')
    fire.append(int(lc[1]))
    print lc[1]

But as someone has already suggested, you can do that in one line, with list comprehension:

newlist = [int(current[1]) for current in line.split(" ") for line in lst]

Which reads like: for ever line in lst we split the line with whitespace, and add element with index one from splitted line (current[1]) converted to int, to our new list.

raceCh-