Flatten a list/tuple and Call a function with tuples

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Jul 26 02:51:33 EDT 2007


On Thu, 26 Jul 2007 00:58:10 +0000, beginner wrote:

> 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:
> 
> Big Record
>    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.

That's where you may start looking into classes.  The simplest one is for
just holding attributes seems to be the "bunch":

In [15]: class Bunch(object):
   ....:     def __init__(self, **kwargs):
   ....:         self.__dict__ = kwargs
   ....:

In [16]: small_a = Bunch(foo=42, bar=23)

In [17]: many_b = [1, 2, 3]

In [18]: small_c = Bunch(name='eric', profession='viking')

In [19]: big_record = Bunch(small_a=small_a, many_b=many_b, small_c=small_c)

In [20]: big_record.small_a.bar
Out[20]: 23

In [21]: big_record.many_b[1]
Out[21]: 2


> 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[0]..x[n]. There are usually 7-10 items in the list and
> it is very tedious and error prone.

If you are the designer of `f` then just receive the whole `x` as *one*
argument.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list