【发布时间】:2019-09-24 10:01:40
【问题描述】:
我有一个嵌套列表:
A = [['a', 'b', 'c', 'd', 'e'], ['a', 'a', 'b', 'c'], ['b', 'c'], ['a', 'd']]
我想将列表 A 保存到多个文本文件中,每个文本文件限制为 2 个嵌套列表。
所以输出应该是这样的:
在small_file_2.txt:
a
b
c
d
e
a
a
b
c
在small_file_4.txt:
b
c
a
d
我试过这段代码:
lines_per_file = 2
for lineno, line in enumerate(A):
if lineno % lines_per_file == 0:
if smallfile:
smallfile.close()
small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
smallfile = open(small_filename, "w")
smallfile.write('\n'.join(str(x) for x in line)+'\n')
smallfile.close()
不幸的是,文本文件中的输出与我预期的不同。它不会在每个新的嵌套列表之后打印换行符。
【问题讨论】:
-
请修正缩进。
smallfile.write缩进错误。
标签: python list-comprehension nested-lists