Python如何读取和分割一行到几个整数

Sta*_*tan 7 python file-io

对于由空格/制表符分隔的输入文件,如:

1 2 3
4 5 6
7 8 9
Run Code Online (Sandbox Code Playgroud)

如何读取行并拆分整数,然后保存到列表或元组中?谢谢.

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
Run Code Online (Sandbox Code Playgroud)

Jef*_*rry 11

一种方法,假设子列表位于不同的行上:

with open("filename.txt", 'r') as f:
    data = [map(int, line.split()) for line in f]
Run Code Online (Sandbox Code Playgroud)

请注意,该with声明直到Python 2.6才成为官方声明.如果您使用的是早期版本,则需要执行此操作

from __future__ import with_statement
Run Code Online (Sandbox Code Playgroud)