简体   繁体   中英

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM