tags:

views:

126

answers:

5

For input file separate by space/tab like:

1 2 3
4 5 6
7 8 9

How to read the line and split the integers, then save into either lists or tuples? Thanks.

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
+4  A: 

One way to do this, assuming the sublists are on separate lines:

with open("filename.txt", 'r') as f:
    data = [map(int, line.split()) for line in f]

Note that the with statement didn't become official until Python 2.6. If you are using an earlier version, you'll need to do

from __future__ import with_statement
Jeff Bradberry
+1 this is closest to the way I'd do it, and I think the best example of "best practices" (whatever that means) of the 5 answers here.
David Zaslavsky
+2  A: 

tuples = [tuple(int(s) for s in line.split()) for line in open("file.txt").readlines()]

I like Jeff's map(int, line.split()), instead of the inner generator.

Stephen
Does this way really store a splited line into a tuple? Can you please explain a bit more? Thanks.
Stan
Actually this will give you a list of lists, not a list of tuples (because `str.split` returns a list). Basically what it does is open the file, read in its lines, then iterate through them (`for tup in ...`) and split each one on whitespace.
David Zaslavsky
So how to store in a tuple? That is part of my original question. Thanks.
Stan
one liners are cool
Justin L.
@David : the OP said lists or tuples, but good call, thanks, edited. @Stan : just construct a tuple from the list.
Stephen
@Stephen: yep, my comment was directed to Stan's comment above mine, not so much at your answer. Sorry for not making that clear.
David Zaslavsky
+1  A: 

You mean, like this?

update

Just convert each string into int

string = """1 2 3
4 5 6
7 8 9"""

data = []
for line in string.split("\n"):    #split by new line
    data.append( map( int, line.split(" ") ) ) # split by spaces and add 

print( data )

Output:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Da daaaa!!!

OscarRyz
nope, I want to save integer in my list, not string.
Stan
And can you figure out from my example? ... it's easy ...
OscarRyz
I end up using mapping function. Still didn't figure out another way to convert all read in string into a integer.
Stan
I just learned how to map from Jeff's answer.
Stan
Oh, I thought you had that already I misread your *I end up using...*
OscarRyz
+1  A: 
def getInts(ln):
    return [int(word) for word in ln.split()]

f = open('myfile.dat')
dat = [getInts(ln) for ln in f]
Hugh Bothwell
+2  A: 

If you find yourself dealing with matrices or tables of numbers, may I suggest numpy package?

import numpy as np
data = np.loadtxt(input_filename)
Dat Chu