python - Python文件读取行从startswith到endswith并移动到列表
问题描述
我有如下文件:
=======
line1 contents
line2 contents
line3 contents
=======
=======
line4 contents
line5 contents
=======
=======
line6 contents
line7 contents
=======
读取以 ======= 开头到以 ======= 结尾的文件内容。将输出发送到列表。
以下是列表列表的预期输出
[["line1 contents", "line2 contents", "line3 contents"],
["line4 contents", "line5 contents"],
["line6 contents", "line7 contents"]]
解决方案
假设您的输入文本存储在 variable 中s
,您可以使用以下列表推导:
[l.splitlines() for l in s.split('=======\n')[1::2]]
使用您的示例输入,这将返回:
[['line1 contents', 'line2 contents', 'line3 contents'], ['line4 contents', 'line5 contents'], ['line6 contents', 'line7 contents']]
推荐阅读
- android - Foreign 不适用于 SQLite(在 DB 中返回 Null)
- node.js - 在 NodeJs 中调用第三方 API
- javascript - 如果empty = true,则从双嵌套数组中删除第一项和最后一项
- mysql - SQL - 按日期排序 5 行后递增
- mqtt - 保留未在 MQTT 客户端中格式化的消息
- c - 我如何从文件中读取变量?
- python - 如何在我的 pygame 项目中修复子弹?
- arrays - 尝试使用 vba 在 Excel 中创建数组后过滤时出错
- c# - wpf中的宽度值是如何传递的
- sql - 如何在“何时”逻辑中的基本“案例”选择器中使用 SQL 比较器,而无需重新编写条件