[Tutor] How to foreach over a dynamic number of levels
Kent Johnson
kent37 at tds.net
Thu Feb 12 19:35:42 CET 2009
On Thu, Feb 12, 2009 at 1:04 PM, Alexander Daychilde (Gmail)
<daychilde at gmail.com> wrote:
>> 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?
The docs for itertools.product() give a pure-Python equivalent, just
paste that into your code:
http://docs.python.org/library/itertools.html#itertools.product
> 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.
Maybe you should use a list of pairs (tuples) where the first element
is the name and the second is the list of models:
steps = [
('model1', ['some_model1']),
('model2', ['some_model2', 'othermodel2'])
# etc
]
You could perhaps modify the product() function to create the strings
you need. You might want to get a little practice working with lists
first...
Kent
More information about the Tutor
mailing list