nesting for statements?

Peter Otten __peter__ at web.de
Tue Nov 29 03:05:27 EST 2005


tpcolson at gmail.com wrote:

> Hi. Thanks for the tip. However, implementing that example, the script
> will only generate the second output "file", (or it's overwriting the
> first one), so all I get when run is "fileb".

I think your looping code has the structure

for x in ["a", "b", "c"]:
   pass
print x 

This will print x once after the loop has completed. By then the value of x
is "c". To fix it, move the code from /after/ the loop /into/ the loop:

for x in ["a", "b", "c"]:
    print x

In the code you give that would mean that you have to indent the

try:
    # ...
except:
    # ...

statement one more level.

Inside that loop you want a filename and an integer value in lockstep. The
simplest way to get that is zip():

>>> for Disc, suffix in zip(xrange(2, 6, 2), "abcdefghijklmnopqrstuvwxyz"):
...     Out_Dem = "out" + suffix
...     print Disc, Out_Dem
...
2 outa
4 outb

Again, you have to replace the print statement by your try...except. If you
fear that you will eventually run out of suffices, here is a function that
"never" does:

>>> def gen_suffix(chars):
...     for c in chars:
...             yield c
...     for c in gen_suffix(chars):
...             for d in chars:
...                     yield c + d
...
>>> for i, s in zip(range(20), gen_suffix("abc")):
...     print i, s
...
0 a
1 b
2 c
3 aa
4 ab
5 ac
6 ba
7 bb
8 bc
9 ca
10 cb
11 cc
12 aaa
13 aab
14 aac
15 aba
16 abb
17 abc
18 aca
19 acb

That said, reading the tutorial or an introductory book on Python never
hurts...

Peter




More information about the Python-list mailing list