Variable depth of nesting
Andrew Cooke
andrew at intertrader.com
Wed Feb 7 09:30:42 EST 2001
I think this is "Power Loops" - see the first chapter (IIRC) of Finkel
at http://cseng.aw.com/book/related/0,3833,0805311912+20,00.html
(although I may be wrong as they never made much sense to me and my
brand-spanking-new firewall won't let me look at the book that URL
indicates any more because it's FTP).
Andrew
Jacek Generowicz wrote:
>
> Is it somehow possible to write loops with variable nesting depths?
>
> For example, I would like to write something like the function
> outlined below without having to use the if clauses. Particularly, I
> would like to make it work for a GENERAL length of list_of_lists.
>
> def hmm ( list_of_lists ):
> if len( list_of_lists ) == 1:
> for x in list_of_lists[0]:
> # do something
> return
>
> if len( list_of_lists ) == 2:
> for x in list_of_lists[0]:
> for y in list_of_lists[1]
> # do somehting
> return
>
> if len( list_of_lists ) == 3:
> for x . . . :
> for y . . . :
> for z . . . :
> # do something
> return
>
> if len( list_of_lists ) == 4:
>
> #etc.
> #etc.
>
> Alternatively, how about list comprehensions with variable order:
>
> def hmm ( l ):
> if len( l ) == 1:
> return [ x for x in l[0] ]
>
> if len( l ) == 2:
> return [ (x,y) for x in l[0] for y in l[1] ]
>
> if len( l ) == 3:
> return [ (x,y,z) for x in l[0] for y in l[1] for z in l[2] ]
>
> #etc.
> #etc.
>
> Any ideas ?
>
> Thanks,
>
> Jacek
More information about the Python-list
mailing list