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

Duncan Booth duncan.booth at invalid.invalid
Tue Sep 4 15:06:38 CEST 2007


cjt22 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).




More information about the Python-list mailing list