【问题标题】:Read a file and generate a list of lists using list comprehensions读取文件并使用列表理解生成列表列表
【发布时间】:2023-01-26 15:51:48
【问题描述】:
我想读取一个包含以下输入的文件:
10
20
30
50
60
70
80
90
100
并生成以下输出:
[['10', '20', '30'], ['50','60','70'] ... ]
使用列表理解而不是 foor 循环。当然,我面临的问题是在检测到 \n 字符时创建嵌套列表。当然,“免责声明”代码使用 for 循环可能更具可读性!
with open('file.txt', 'r') as f:
result = [line.strip() for line in f.readlines() if line != '\n']
print(result)
//
['10', '20', '30', '50', '60', '70']
// not correct
【问题讨论】:
标签:
python
list-comprehension
【解决方案1】:
关键是第二行的嵌套理解。
(此解决方案不需要 strip。)
with open('file.txt', 'r') as f:
result = [[x for x in s.split("
")] for s in f.read().split("
")]
print(result)
另一种方法使用readlines 和groupby。
with open('file.txt', 'r') as f:
result = [[s.strip() for s in group] for key, group in groupby(f.readlines(), lambda x: x == "
") if not key]
print(result)