Iterating over multiple lists (a newbie question)

Huaiyu Zhu hzhu at users.sourceforge.net
Sun Jan 7 00:01:12 EST 2001


On Thu, 04 Jan 2001 19:55:43 GMT, Victor Muslin <victor at prodigy.net> wrote:
>Thank you all for the insights. Here is another variation on the them,
>though this involves a single list.
>
>Suppose I want to parse command line arguments (never mind getops,
>since this could be some other situation not involving command line
>arguments). Here is how I could possibly parse command line arguments
>for command: "myprog -port 10 -debug":
>
>	import sys
>	debug = port = 0
>	i = 1                                      # ugly
>	while i < len(sys.argv):
>	    if sys.argv[i] == '-debug':
>	        debug=1
>	    elif sys.argv[i] == '-port':
>	        i = i + 1                          # ugly!
>	        if i < len(sys.argv):           # very ugly!
>	            port = int(sys.argv[i])
>	    i = i + 1                              # quite ugly
>
>Pretty ugly, huh? Is there a more elegant way?

I think you are looking for something like the following hyperthetical code

for x in sys.argv:
    if x == '-debug':
        debug = 1
    elif x == '-port':
        next x         # This does not exist now
        port = int(x)

Can this syntax be added to Python?  My take is that it would be difficult
to design a good syntax, but not difficult to implement. This is because the
"next x" must associate the internal loop counter (which is your i) with the
name x.  But what if there are several for loops?  Limiting this to a single
loop is too restrictive.  Maybe someone can come up with a better syntax.

An alternative approach would be to expose the loop counter and let user do
whatever with the loop counter, but that might be too free.

Huaiyu





More information about the Python-list mailing list