Printing lists in columns (was: TypeError: 'module object is not callable')

cjt22 at bath.ac.uk cjt22 at bath.ac.uk
Tue Sep 4 09:43:14 EDT 2007


On Sep 4, 2:06 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> cj... at bath.ac.uk wrote:
> >> But watch out if the lists aren't all the same length: zip won't pad out
> >> any sequences, so it maynotbe exactly what is wanted here:
>
> >> >>> x = ['1', '2', '3']
> >> >>> y = ['4', '5']
> >> >>> for row in zip(x,y):
>
> >>         print ', '.join(row)
>
> >> 1, 4
> >> 2, 5
>
> > Unfortunately the lists will be of different sizes
>
> In that case use:
>
> from itertools import repeat, chain, izip
> def izip_longest(*args, **kwds):
>     fillvalue = kwds.get('fillvalue')
>     def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
>         yield counter()         # yields the fillvalue, or raises IndexError
>     fillers = repeat(fillvalue)
>     iters = [chain(it, sentinel(), fillers) for it in args]
>     try:
>         for tup in izip(*iters):
>             yield tup
>     except IndexError:
>         pass
>
> x = ['1', '2', '3']
> y = ['4', '5']
> for row in izip_longest(x,y, fillvalue='*'):
>     print ', '.join(row)
>
> which gives:
>
> 1, 4
> 2, 5
> 3, *
>
> (izip_longest is in a future version of itertools, but for
> now you have to define it yourself).

Thanks guys

I have a list of lists such as
 a = ["1" , "2"]  b = ["4", "5", "6"]  c = ["7",8", "9"]
Stored in another list: d = [a,b,c]

I know this makes me sound very stupid but how would I specify
in the parameter the inner lists without having to write them all out
such as:

for row in izip_longest(d[0], d[1], d[2], fillvalue='*'):
    print ', '.join(row)

i.e. How could I do the following if I didn't know how many list of
lists I had.
Sorry this sounds stupid and easy.
Thankyou very much in advance as well, you are all very helpful
indeed.




More information about the Python-list mailing list