Flatten a list/tuple and Call a function with tuples
zyzhu2000 at gmail.com
Thu Jul 26 02:58:10 CEST 2007
On Jul 25, 11:33 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> beginner <zyzhu2... at gmail.com> writes:
> > I know the * operator. However, a 'partial unpack' does not seem to work.
> A few other posters have mentioned ways around this, but you might ask
> yourself what coding situation makes you want to do this stuff in the
> first place. I won't say there's never a reason for it, but a lot of
> times, a list containing a mixture of scalars and lists/tuples is a
> sign that your underlying data representation is contorted. Things
> are logically single values or they are logically lists of values, and
> that mixed representation is often a sign that the item logically
> should be a list, and you're hairing up the program with special
> treatment of the case where the list has exactly one element.
> I.e. instead of [[1,2,], 3, [5,6,]] maybe you really want
> [[1,2,], [3,], [5,6]] without the special treatment and flattening.
Very good question. It is well possible that the problem is my
programming style. I am new to python and am still developing a style
that works for me. A lot of things that work in perl does not seem to
work. Unpacking and flattening are just two examples.
I need nested lists to represent nested records in a script. Since the
structure of the underlying data is nested, I think it is probably
reasonable to represent them as nested lists. For example, if I have
the below structure:
Small Record Type A
Many Small Record Type B
Small Record Type C
It is pretty natural to use lists, although after a while it is
difficult to figure out the meaning of the fields in the lists. If
only there were a way to 'attach' names to members of the list.
For the unpacking question, I encountered it when working with list
comprehensions. For example:
[ f(*x,1,2) for x in list] is difficult to do if I don't want to
expand *x to x..x[n]. There are usually 7-10 items in the list and
it is very tedious and error prone.
The second problem is from a nested list comprehension. I just needed
something to flatten the list at the moment.
I am still forming my way to do things in python via trial and error.
It is well possible that this is not the natural way to do things.
More information about the Python-list