Coding Nested Loops

Peter Otten __peter__ at web.de
Fri Sep 15 12:57:05 EDT 2006


Rich Shepard wrote:

>    I want to code what would be nested "for" loops in C, but I don't know
>    the
> most elegant way of doing the same thing in python. So I need to learn how
> from you folks. Here's what I need to do: build a database table of 180
> rows. Each row contains 31 columns: the first is an automatically
> incremented integer as the primary key; the next two fields can each
> contain one of three strings held in dictionaries, the last 28 fields are
> random floats from a third dictionary.
> 
>    Of the 180 total rows, each of the three values in the first dictionary
> will be the second field in 60 rows. Within each set of 60 rows, there
> will be 13 rows containing the first value from the second dictionary, 14
> rows containing the second value from the second dictionary, and 33 rows
> from the third value in that dictionary. Again, the final 28 fields in
> each row are random values from the third dictionary.
> 
>    I suspect that iterators might be the way to accomplish this, but I
>    really
> don't know. However, I would like to learn so that I can solve similar
> problems by myself.

It's not clear to me why you would use dictionaries, especially as they are
unordered; I used lists instead:

from itertools import count, izip, cycle, chain, repeat, starmap, imap
from random import choice

first =  ["X", "Y", "Z"]
second = ["A", "B", "C"]
second_count = [13, 14, 33]
third = [1.1, 2.2, 3.3, 4.4]

random_floats = imap(choice, repeat(third))
columns = [
    count(),
    chain(*[repeat(i, 60) for i in first]),
    cycle(chain(*starmap(repeat, izip(second, second_count))))
]
columns.extend(repeat(random_floats, 28))

for row in izip(*columns):
    print row

Now that is a nice occasion to get acquainted with the itertools module...

Peter




More information about the Python-list mailing list