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

Tim Chase python.list at tim.thechases.com
Mon Jan 9 09:21:43 EST 2017


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




More information about the Python-list mailing list