如何解决Python:导入文本文件以使子列表以“#”分隔
我正在尝试读取文本文件并将其作为子列表。每个子列表由仅包含“#”的行分隔。文本文件示例:
#
1 2
3 4
#
5 6
7 8
这张图片会更好地表示 enter image description here
结果应该是:[[[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)
,
文件:
#
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]]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。