Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for-loop look-ahead

Tags:

python

I have a python for loop, in which I need to look ahead one item to see if an action needs to be performed before processing.

for line in file:
    if the start of the next line == "0":
        perform pre-processing
        ...
    continue with normal processing
    ...

Is there any easy way to do this in python? My current approach is to buffer the file to an array, however this is not ideal as the file is rather large.

like image 999
Mike Avatar asked Nov 16 '10 18:11

Mike


People also ask

What can I use instead of a for loop in Python?

Map() Function in Python The map() function is a replacement to a for a loop. It applies a function for each element of an iterable.

Does Python have C style for loops?

JavaScript, C, C++, Java, PHP, and a whole bunch of other programming languages all have this kind of for loop. But Python does not. Python does not have traditional C-style for loops. We do have something that we call a for loop in Python, but it works like a foreach loop.

How do you do a simple loop in Python?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

What is for loop in Python example?

The for loop in Python is used to iterate over a sequence, which could be a list, tuple, array, or string. The program operates as follows: We have assigned a variable, x, which is going to be a placeholder for every item in our iterable object.


2 Answers

you can get any iterable to prefetch next item with this recipe:

from itertools import tee, islice, izip_longest
def get_next(some_iterable, window=1):
    items, nexts = tee(some_iterable, 2)
    nexts = islice(nexts, window, None)
    return izip_longest(items, nexts)

Example usage:

for line, next_line in get_next(myfile):
    if next_line and next_line.startswith("0"):
        ... do stuff

The code allows you to pass the window parameter as a larger value, if you want to look 2 or more lines ahead.

like image 186
nosklo Avatar answered Sep 18 '22 11:09

nosklo


Along the lines of nosklo's answer, I tend to use the following pattern:

The function pairwise from the excellent itertools recipes is ideal for this:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

Using it in your code gets us:

for line, next_line in pairwise(file):
    if next_line.startswith("0"):
        pass #perform pre-processing
        #...
    pass #continue with normal processing

Generally, for this type of processing (lookahead in the iterable), I tend to use a window function. Pairwise is a special case of a window of size 2.

like image 39
Muhammad Alkarouri Avatar answered Sep 21 '22 11:09

Muhammad Alkarouri