0

我正在尝试读取文本文件并将其作为子列表。每个子列表由仅包含“#”的行分隔。文本文件示例:

#
1  2
3  4
#
5  6
7  8

此图像将是更好的表示 在此处输入图像描述

结果应该是:[[[1,2],[3,4]], [[5,6],[7,8]]]

这就是我想出的:

file=open(file_name)
contents=[]
for row in file:
    stripped_row=row.strip()
    row_list=stripped_row.split()
    contents.append(row_list)
file.close()

我得到的结果是[['#'], ['2.1,-3.1'], ['-0.7,4.1'], ['#'], ['3.8,1.5'], ['-1.2,1.1']]

4

2 回答 2

1

我会用嵌套列表理解来做到这一点。

with open(file_name) as file_handle:
    contents = [
        [
            [
                float(item)
                for item in line.split()
            ]
            for line in block.strip().splitlines()
        ]
        for block in file_handle.read().strip('#\r\n').split('#')
    ]
print (content)

于 2021-04-16T08:07:19.540 回答
0

文件:

#
2.1 -3.1
-0.7 4.1
#
3.8 1.5
-1.2 1.1

代码:

with open("file.txt") as f:
    contents=[]
    for row in f:
        if not row.startswith("#"):
            line_data=[]
            for x in row.split():
                line_data.append(float(x))
            contents.append(line_data)
print(contents)

结果:

[[2.1, -3.1], [-0.7, 4.1], [3.8, 1.5], [-1.2, 1.1]]
于 2021-04-16T07:58:19.683 回答