Using namedtuples field names for column indices in a list of lists
breamoreboy at gmail.com
breamoreboy at gmail.com
Mon Jan 9 17:16:41 EST 2017
On Monday, January 9, 2017 at 5:34:12 PM UTC, Tim Chase wrote:
> On 2017-01-09 08:31, breamoreboy 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
> > 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.
>
> 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
> pairing
def ntuplewise(iterable, n=2):
args = tee(iterable, n)
loops = n - 1
while loops:
for _ in range(loops):
next(args[loops], None)
loops -= 1
return zip(*args)
>
> 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)
Use zip_longest instead of zip in the example code above.
> # or
> (PADDING, s0), (s0, s1), (s1, s2)
Haven't a clue off of the top of my head and I'm too darn tired to think about it :)
>
> but it's good to have my common cases already coded & tested.
>
> -tkc
Kindest regards.
Mark Lawrence.
More information about the Python-list
mailing list