简体   繁体   中英

Python while, continue loops

My input file is one sentence per line. Let's say it looks like:

A
B
C
D
E
F

Desired output is:

::NewPage::
A
B
::NewPage::
C
D
::NewPage::
E
F

I know that I should be using a while loop but not sure how to?

You don't need a while loop here - look at the grouper recipe in itertools .

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)

Note that you will need a slightly different version if you are using 2.x.

Eg:

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)

Which produces:

::NewPage::
A
B
::NewPage::
C
D
::NewPage::
E

If you need None values, you can use a sentinel object.

I dont know if this might bother the gods of the PEP-8.

But a language agnostic alternative (understandable by a more generic audience) might be:

items = ["A", "B", "C", "D", "E"]
out = []

for i,item in enumerate(items):
    if i%2 == 0:
        out.append("::New Page::")
    out.append(item)

Edit: this is what happens when you dont check if there's a new answer before finishing writing yours. My answer is basicallly the same as cdarke's.

Like this? Tested on 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 = []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM