我的输入文件是每行一句话。假设它看起来像这样:
A
B
C
D
E
F期望的输出为:
::NewPage::
A
B
::NewPage::
C
D
::NewPage::
E
F我知道我应该使用while循环,但不确定如何使用?
发布于 2012-10-11 20:29:37
这里不需要while循环--看看itertools中的the grouper recipe。
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)请注意,如果您使用的是2.x,则需要a slightly different version。
例如:
items = ["A", "B", "C", "D", "E"]
for page in grouper(2, items):
print("::NewPage::")
for item in page:
if item is not None:
print(item)这会产生:
::NewPage::
A
B
::NewPage::
C
D
::NewPage::
E如果需要None值,可以使用sentinel对象。
发布于 2012-10-11 20:44:00
我不知道这是否会困扰PEP-8的众神。
但另一种语言不可知的选择(更一般的受众可以理解)可能是:
items = ["A", "B", "C", "D", "E"]
out = []
for i,item in enumerate(items):
if i%2 == 0:
out.append("::New Page::")
out.append(item)编辑:这就是当你在写完你的答案之前没有检查是否有新的答案时发生的事情。我的答案与cdarke的答案基本相同。
发布于 2012-10-11 20:35:58
是像这样吗?在Python 3.3上测试:
i = 0
page_size = 2
lines = []
for line in open("try.txt"):
lines.append(line)
i += 1
if i % page_size == 0:
print("::NewPage::")
print("".join(lines),end="")
i = 0
lines = []https://stackoverflow.com/questions/12839529
复制相似问题