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

Peter Otten __peter__ at web.de
Mon Jan 9 19:09:46 EST 2017


breamoreboy at gmail.com wrote:

> 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 :)

In both cases modify the iterable before feeding it to ntuplewise():

>>> PADDING = None
>>> N = 3
>>> items = range(5)
>>> list(ntuplewise(chain(repeat(PADDING, N-1), items), N))
[(None, None, 0), (None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, 4)]
>>> list(ntuplewise(chain(items, repeat(PADDING, N-1)), N))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, None), (4, None, None)]




More information about the Python-list mailing list