来自txt文件的示例行:
one
two
three
one1
two2
three3
期望的结果:
['one', 'two', 'three']
['one1', 'two2', 'three3']
如何将每3行合并为1并转换为列表?
我希望这能继续通过一个包含数百行的大文本文件。
此代码我从另一个帖子中获取了它每行仅合并2个
f = open('joining-lines-template.txt')
mod_list = []
count = 1
for line in f:
line = line.rstrip()
if count % 2 == 0:
mod_list.append(old_line+line)
else:
old_line = line
count += 1
print(mod_list)
澄清
打印时的最终输出应如下所示,新行上的列表而不是一行上的列表。
['one','two','three']
['one1','two2','three3']
答案 0 :(得分:2)
我会完全读取该文件,然后使用切片3乘3创建列表理解:
with open("input.txt") as f:
lines = list(f) # convert file to list of lines so slicing works
result = [lines[i:i+3] for i in range(0,len(lines),3) ]
Variant:这是一种不需要一次读取所有文件的方法:
with open("input.txt") as f:
result = [[l,next(f),next(f)] for l in f]
但是节省内存需要付出代价:
初学者可能喜欢完整的“经典”python代码:
result = []
sublist = []
for l in f:
sublist.append(l)
if len(sublist)==3:
result.append(sublist)
sublist = []
if sublist:
result.append(sublist)
在所有情况下,只需要打印列表列表:
for l in result:
print(l) # prints the representation of the sublist