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

Tim Chase python.list at
Mon Jan 9 12:08:30 EST 2017

On 2017-01-09 08:31, breamoreboy at wrote:
> On Monday, January 9, 2017 at 2:22:19 PM UTC, Tim Chase wrote:
> > I usually wrap the iterable in something like
> > 
> >   def pairwise(it):
> >     prev = next(it)
> >     for thing in it:
> >       yield prev, thing
> >       prev = thing
> Or from
> 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. 

Ah, helpful to not have to do it from scratch each time.  Also, I see
several others that I've coded up from scratch (particularly the
partition() and first_true() functions).

I usually want to make sure it's tailored for my use cases. The above
pairwise() is my most common use case, but I occasionally want N-wise

  s -> (s0,s1,…sN), (s1,s2,…S{N+1}), (s2,s3,…s{N+2}), …

or to pad them out so either the leader/follower gets *all* of the
values, with subsequent values being a padding value:

  # lst = [s0, s1, s2]
  (s0,s1), (s1, s2), (s2, PADDING)
  # or
  (PADDING, s0), (s0, s1), (s1, s2)

but it's good to have my common cases already coded & tested.


More information about the Python-list mailing list