Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to read and split a line to several integers

Tags:

python

file-io

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)]
like image 985
Stan Avatar asked Jun 25 '10 23:06

Stan


1 Answers

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
like image 171
Jeff Bradberry Avatar answered Sep 21 '22 06:09

Jeff Bradberry