Using namedtuples field names for column indices in a list of lists

breamoreboy at gmail.com breamoreboy at gmail.com
Mon Jan 9 11:31:55 EST 2017


On Monday, January 9, 2017 at 2:22:19 PM UTC, Tim Chase wrote:
> On 2017-01-08 22:58, Deborah Swanson wrote:
> > 1) I have a section that loops through the sorted data, compares two
> > adjacent rows at a time, and marks one of them for deletion if the
> > rows are identical.
> > 
> > I'm using 
> > 
> > for i in range(len(records)-1):
> >     r1 = records[i]
> >     r2 = records[i+1]
> >     if r1.xx = r2.xx:
> > 		.
> > 		.
> > and my question is whether there's a way to work with two adjacent
> > rows without using subscripts?  
> 
> I usually wrap the iterable in something like
> 
>   def pairwise(it):
>     prev = next(it)
>     for thing in it:
>       yield prev, thing
>       prev = thing
> 
>   for prev, cur in pairwise(records):
>     compare(prev, cur)
> 
> which I find makes it more readable.
> 
> -tkc

Or from https://docs.python.org/3/library/itertools.html#itertools-recipes:-

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

This and many other recipes are available in the more-itertools module which is on pypi.



More information about the Python-list mailing list