python - 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']]
解决方案
我会用嵌套列表理解来做到这一点。
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)
推荐阅读
- logging - nagios.log 格式 - 字段定义
- php - 提交前强制引导表单验证?
- go - Golang 未签名 URL
- c - 代码不打印数组中的字符
- r - 如何在 R 中使用粘贴,在新列中没有间隙?
- django - Django 在不知道文件名的情况下显示带注释的查询集的值
- c - C中的灵活数组的灵活数组
- c++ - 在另一个成员函数的尾随返回类型中获取推导成员函数的 decltype 是否格式正确?
- asp.net-core - 当 Web 应用程序对访问者及其自身向 Microsoft Graph 进行身份验证时,身份验证流程
- ruby-on-rails - After_udpate rails 回调失败测试