[Tutor] How to foreach over a dynamic number of levels

Alexander Daychilde (Gmail) daychilde at gmail.com
Thu Feb 12 19:04:05 CET 2009


First, thank you VERY much for your help! That's amazingly much easier than
I thought it would be... I was considering looping through and generating
nested for loops, then exec'ing the whole mess.. UGH, and security risk, to
boot...

Couple of questions:

> Make a list containing all the steps:
> steps = [step1, step2, step3]
> 
> Now you need to convert all steps to lists. This loop builds a new
> list from the original step list, wrapping any bare strings in lists:
> 
> step_lists = []
> for step in steps:
>     if isinstance(step, basestring):
>         step = [step]
>     step_lists.append(step)
> 
> Now what you want is the Cartesian product of all the lists. Python
> has a function (new in Python 2.6) in the itertools library module
> that will do this:

I'm stuck on 2.5.2 because of the framework I'm driving... Does that
preclude this solution?

> from itertools import product
> for model_set in product(*step_lists):
>     print model_set
> 
> (The * in the argument list means, take the elements of step_list and
> use them as the arguments to product())
> 
> The output is
> ('step1model-a', 'step2model-a', 'step3model-a')
> ('step1model-a', 'step2model-a', 'step3model-b')
> ('step1model-b', 'step2model-a', 'step3model-a')
> ('step1model-b', 'step2model-a', 'step3model-b')
> ('step1model-c', 'step2model-a', 'step3model-a')
> ('step1model-c', 'step2model-a', 'step3model-b')

I hate to ask such a n00b question, but I am still learning python, and I
must just be missing how to do this: How can I reference the key name as
well?

Basically, what I'm imputing is more like this:

date = {2008-01-01:2008-01-30} # I'll parse that into 30 days
model1 = some_model1
model2 = {some_model2;othermodel2} # I'll parse into a real list
[...]
somekey = somevalue

What I'm outputting is a series of INI files, one for each run. In this
case, that's 30 days times the two models, but since any key/value pair can
be an array, it may end up being hundreds or thousands (or millions) of
runs...

For each run, I output something like this:

date = 2008-01-01
model1 = some_model1
model2 = some_model2
[...]
somekey = somevalue


So I have to be able to regurgitate the key name -- and  I'm not sure how to
address that... Like in PHP, I'd use a variable variable.

(I feel like this is a st00pid n00b question, and if so, I do apologize, but
I'm just... missing it somewhere... I'm honestly trying to improve my coding
skills, but you know how it is - you don't know something until you learn
it... and python is in some ways refreshing and awesome, and in some ways
just blowing my mind...)

> HTH
> Kent

Very much, indeed! :)



More information about the Tutor mailing list