7

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)]
Stan
  • 37,207
  • 50
  • 124
  • 185

5 Answers5

11

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,597
  • 1
  • 12
  • 11
  • +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 Z Jun 26 '10 at 00:30
3

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
  • 10,822
  • 13
  • 58
  • 82
2

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.

Community
  • 1
  • 1
Stephen
  • 47,994
  • 7
  • 61
  • 70
  • Does this way really store a splited line into a tuple? Can you please explain a bit more? Thanks. – Stan Jun 26 '10 at 00:23
  • 1
    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 Z Jun 26 '10 at 00:29
  • So how to store in a tuple? That is part of my original question. Thanks. – Stan Jun 26 '10 at 00:32
  • 1
    @David : the OP said lists or tuples, but good call, thanks, edited. @Stan : just construct a tuple from the list. – Stephen Jun 26 '10 at 01:04
  • @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 Z Jun 26 '10 at 01:49
1

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
  • 196,001
  • 113
  • 385
  • 569
  • I end up using mapping function. Still didn't figure out another way to convert all read in string into a integer. – Stan Jun 26 '10 at 00:11
  • Oh, I thought you had that already I misread your *I end up using...* – OscarRyz Jun 26 '10 at 00:24
1
def getInts(ln):
    return [int(word) for word in ln.split()]

f = open('myfile.dat')
dat = [getInts(ln) for ln in f]
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99