行数在一开始就已知.
0 1 2 3 4 5 6 7 8
8 1 2 3 4 5 6 7 0
4 0 8 2 6 3 7 1 5
..n such lines
Run Code Online (Sandbox Code Playgroud)
line1 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
line2 = [8, 1, 2, 3, 4, 5, 6, 7, 0]
line3 = [4, 0, 8, 2, 6, 3, 7, 1, 5]
.
.
linen = [n1, ........ n9]
Run Code Online (Sandbox Code Playgroud)
我现在在:
#The lines start at the 7th byte in the input file.
f.seek(7)
#Getting rid of the '\r\n'
lines = [line.rstrip('\n\r') for line in f]
#1st line
line0 = lines[0]
line = [[int(i) for i in line0.split()]]
print line
...& so on for the 'n' lines
Run Code Online (Sandbox Code Playgroud)
str.split()已经从末尾删除了空格,包括换行符.没有必要剥离\r; Python已经将行分隔符转换为just \n.
不要试图分配多个line*变量; 只需使用列表:
with open(filename, 'r') as fobj:
all_lines = [[int(num) for num in line.split()] for line in fobj]
Run Code Online (Sandbox Code Playgroud)
现在您有一个包含整数的列表.
您可以在从文件中读取每行时处理它们; 当时转向最终产品,而不是将所有行保留在内存中:
with open(filename, 'r') as fobj:
for line in fobj:
numbers = [int(num) for num in line.split()]
# do something with this line of numbers before moving on to the next.
Run Code Online (Sandbox Code Playgroud)
只需拆分并映射到int,split将为您完成所有工作:
with open("in.txt") as f:
for line in f:
print(map(int,line.split())) # list(map(int,line.split())) for py3
Run Code Online (Sandbox Code Playgroud)
要获取列表列表,请使用列表解析:
with open("in.txt") as f:
data = [map(int,line.split()) for line in f]
Run Code Online (Sandbox Code Playgroud)
如果你使用python3,你需要使用python3 list(map...中的map返回和迭代器与python2中的列表.
您还可以使用dict按名称/键访问每个列表,但您可以使用索引,因此dict将毫无意义.
| 归档时间: |
|
| 查看次数: |
5986 次 |
| 最近记录: |