首页 > 解决方案 > Python:导入文本文件以使子列表以“#”分隔

问题描述

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

#
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']]

标签: pythonpython-3.xreadfilesublist

解决方案


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

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)


推荐阅读