Coding Nested Loops
Peter Otten
__peter__ at web.de
Sat Sep 16 02:32:48 EDT 2006
Rich Shepard wrote:
> On Fri, 15 Sep 2006, Peter Otten wrote:
>
>> It's not clear to me why you would use dictionaries, especially as they
>> are unordered; I used lists instead:
>
> ...
>
>> Now that is a nice occasion to get acquainted with the itertools
>> module...
>
> Peter,
>
> I have to study the docs to understand what's going on. But, I can see
> that this would work.
As George hinted, I went a bit over the top with my itertools example. Here
is a translation into static lists (mostly):
from itertools import izip
from random import choice
first = ["X", "Y", "Z"]
second = ["A", "B", "C"]
third = [1.1, 2.2, 3.3, 4.4]
x, y, z = first
a, b, c = second
def random_floats(sample):
while 1:
yield choice(sample)
columns = [
range(180),
[x]*60 + [y]*60 + [z]*60,
([a]*13 + [b]*14 + [c]*33) * 3] + [random_floats(third)]*28
for row in izip(*columns):
print row
Of course nested loops will work, too. Use whatever you find easiest to
maintain.
Peter
More information about the Python-list
mailing list