Python how to read and split a line to several integers
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
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)
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.
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!!!
def getInts(ln):
return [int(word) for word in ln.split()]
f = open('myfile.dat')
dat = [getInts(ln) for ln in f]
精彩评论