unpaking sequences of unknown length
Anthra Norell
anthra.norell at tiscalinet.ch
Mon Aug 28 03:06:14 EDT 2006
I get it!
>>> def f (*a):
print a
print zip (a) # My mistake
print zip (*a) # Gerard's solution.
>>> f (l1, l2, l3)
([1, 2, 3], [4, 5, 6], [7, 5, 34]) # Argument: tuple of lists
[([1, 2, 3],), ([4, 5, 6],), ([7, 5, 34],)] # My mistake
[(1, 4, 7), (2, 5, 5), (3, 6, 34)] # That's what I want
Thank you all
Frederic
----- Original Message -----
From: "Gerard Flanagan" <grflanagan at yahoo.co.uk>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Sunday, August 27, 2006 2:59 PM
Subject: Re: unpaking sequences of unknown length
>
> 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
>
> --
> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list