在Python中,如何从空格分隔的.txt文件中获取整数列表,并在多行上使用'\ r \n'分隔数字?

Ket*_*omp 7 python

行数在一开始就已知.

输入文件:

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)

我现在在:

  • 在每一行上划分'\ r \n'的文件
  • 获取每一行使用.split()分隔空格和int(i)转换为整数

码:

#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)

Mar*_*ers 6

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)


Pad*_*ham 5

只需拆分并映射到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将毫无意义.