something for itertools

Tim Williams tim at tdw.net
Sat Sep 16 00:28:12 CEST 2006


On 15/09/06, Daniel Nogradi <nogradi at gmail.com> wrote:
> In a recent thread,
> http://mail.python.org/pipermail/python-list/2006-September/361512.html,
> a couple of very useful and enlightening itertools examples were given
> and was wondering if my problem also can be solved in an elegant way
> by itertools.
>
> I have a bunch of tuples with varying lengths and would like to have
> all of them the length of the maximal and pad with None's. So
> something like
>
> a = ( 1, 2, 3 )
> b = ( 10, 20 )
> c = ( 'x', 'y', 'z', 'e', 'f' )
>
> should turn into
>
> a = ( 1, 2, 3, None, None )
> b = ( 10, 20, None, None, None )
> c = ( 'x', 'y', 'z', 'e', 'f' )
>

or maybe a one liner  :)

>>> (a + 5*(None,))[:5]
(1, 2, 3, None, None)

>>> pad_to = 5
>>> (a + pad_to*(None,))[:pad_to]
(1, 2, 3, None, None)
>>> (b + pad_to*(None,))[:pad_to]
(10, 20, None, None, None)
>>> (c + pad_to*(None,))[:pad_to]
('x', 'y', 'z', 'e', 'f')
>>>


-- 

Tim Williams



More information about the Python-list mailing list