Python如何读取和分割一行到几个整数 [英] Python how to read and split a line to several integers
本文介绍了Python如何读取和分割一行到几个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
1 2 3
4 5 6
7 8 9
如何读取行并拆分整数,然后保存到列表或元组?
pre $ data = [[1,2,3],[4,5,6],[7,8, 9]]
$ p $一个方法来做到这一点,假设子列表是分开的行:
data = [(1,2,3),(4,5,6),(7,8,9)]
pre $ 用open(filename.txt,'r')作为f:
data = [map(int,line.split())for line in f]
请注意,与
语句没有成为官方直到Python 2.6。如果您使用的是早期版本,则需要从__future__ import with_statement
$ c
$ c>
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
这篇关于Python如何读取和分割一行到几个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文