unpaking sequences of unknown length
Gerard Flanagan
grflanagan at yahoo.co.uk
Sun Aug 27 08:59:52 EDT 2006
Anthra Norell wrote:
> Hi,
>
> I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this:
>
> def tabulate_lists (*arbitray_number_of_lists):
> table = zip (arbitray_number_of_lists)
> for record in table:
> # etc ...
>
> This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of arguments
maybe I don't understand the problem properly, but you can use '*args'
as 'args' or as '*args', if you see what I mean!, ie.
def tabulate_lists (*arbitray_number_of_lists):
table = zip (*arbitray_number_of_lists)
for record in table:
# etc ...
for example:
def sum_columns(*rows):
for col in zip(*rows):
yield sum(col)
for i, s in enumerate( sum_columns( [1,2], [3,2], [5,1] ) ):
print 'Column %s: SUM=%s' % (i,s)
Column 0: SUM=9
Column 1: SUM=5
-----------------------------------------------------
alternatively:
import itertools as it
def sum_columns2( iterable ):
for col in it.izip( *iterable ):
yield sum(col)
def iter_rows():
yield [1,2]
yield [3,2]
yield [5,1]
print list( sum_columns2( iter_rows() ) )
#(izip isn't necessary here, zip would do.)
-----------------------------------
Gerard
More information about the Python-list
mailing list