Skip to content Skip to sidebar Skip to footer

Perform An Operation During The Last Iteration Of A For Loop In Python

I have a loop that is parsing lines of a text file: for line in file: if line.startswith('TK'): for item in line.split(): if item.startwith('ID='):

Solution 1:

Just refer to the last line outside the for loop:

for line in file:
    if line.startswith('TK'):
        item = Nonefor item in line.split():
            if item.startwith('ID='):
                # *stuff*if item isnotNone:
            # *stuff*

The item variable is still available outside the for loop:

>>>for i inrange(5):...print i... 
0
1
2
3
4
>>>print'last:', i
last: 4

Note that if your file is empty (no iterations through the loop) item will not be set; this is why we set item = None before the loop and test for if item is not None afterwards.

If you must have the last item that matched your test, store that in a new variable:

for line in file:
    if line.startswith('TK'):
        lastitem = Nonefor item in line.split():
            if item.startwith('ID='):
                lastitem = item
                # *stuff*if lastitem isnotNone:
             # *stuff*

Demonstration of the second option:

>>>lasti = None>>>for i inrange(5):...if i % 2 == 0:...        lasti = i...>>>lasti
4

Solution 2:

Try this:

for line in file:
    if line.startswith('TK'):
        items = line.split()
        num_loops = len(items)
        for i in range len(items):
            item = items[i]
            if item.startwith('ID='):
                *stuff*
            if i==num_loops-1: # if last_iteration_of_loop
                *stuff*

Hope that helps

Solution 3:

Not sure why you can't just amend outside the final loop, but you may be able to make use of this - which works with any iterator, not just those of known length...

not extensively tested and possibly not efficient

from itertools import tee, izip_longest, count

defsomething(iterable):
    sentinel = object()
    next_count = count(1)

    iterable = iter(iterable)
    try:
        first = next(iterable)
    except StopIteration:
        yield sentinel, 'E', 0# emptyyield first, 'F', next(next_count) # first

    fst, snd = tee(iterable)
    next(snd)
    for one, two in izip_longest(fst, snd, fillvalue=sentinel):
        yield one, 'L'if two is sentinel else'B', next(next_count) # 'L' = last, 'B' = body

Post a Comment for "Perform An Operation During The Last Iteration Of A For Loop In Python"