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)] 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 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.
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. 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!!!