[英]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. 请注意,在Python 2.6之前,
with
语句才成为官方声明。 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? 如果你发现自己处理矩阵或数字表,我可以建议numpy包吗?
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()] 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. 我喜欢杰夫的
map(int, line.split())
,而不是内部生成器。
You mean, like this?
你的意思是,像这样?
update 更新
Just convert each string into int 只需将每个字符串转换为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']]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Da daaaa!!! Da daaaa !!!
def getInts(ln):
return [int(word) for word in ln.split()]
f = open('myfile.dat')
dat = [getInts(ln) for ln in f]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.