Iterating over multiple lists (a newbie question)
Victor Muslin
victor at prodigy.net
Fri Jan 5 22:19:41 EST 2001
Thanks, but I must have not been very clear. The fact that my example was
parsing command line arguments is incidental. The point was that it is nice to
have a clean iteration over a list as in:
for item in list:
but this nice paradigm breaks down when you have to move the iterator along the
list inside a loop under certain conditions. Then you are into the ugliness of
iteration via indexes. If there were another method associated with a list
object to move the iterator it would have been very useful.
On Fri, 05 Jan 2001 00:50:32 GMT, "Greg Jorgensen" <gregj at pobox.com> wrote:
>Here's a somewhat generalized parser for simple argument/parameter strings
>like command lines. You'll probably want to make it into a function or a
>class for real-world use.
>
>--
>Greg Jorgensen
>PDXperts
>Portland, Oregon, USA
>gregj at pobox.com
>
>
>
># command line or other string to parse
>commandline = '-log -port 25 -file -debug -bogus dummy'
>
># args is keyed by the valid argument names
># args[arg] = 1 if -arg expects a parameter, else args[arg] = 0
>args = { 'debug':0, 'port':1, 'file':1, 'log':0 }
>
># argp will contain the parsed argument list
># add any default values to argp here
>argp = {'log':0, 'port':20}
>
>errmsg = ''
>paramkey = ''
>for a in commandline.split():
> if a[0] == '-': # -argument
> a = a[1:].lower()
> p = args.get(a, -1) # get parameter flag, default to 0
> paramkey = ''
> if p == 1: # next parameter will be associated with
>args[a]
> paramkey = a
> elif p == 0: # no parameter expected
> argp[a] = ''
> else:
> errmsg += 'unexpected argument: -%s\n' % a
> else: # parameter found...
> if paramkey: # which argument does it belong to?
> argp[paramkey] = a
> paramkey = ''
> else:
> errmsg += 'unexpected value: %s\n' % a
>
># let's see the result
>if errmsg:
> print 'errors:\n' + errmsg
>
>print 'parsed arguments:'
>for e in argp.keys():
> if argp[e]:
> print '-%s %s' % (e, argp[e]),
> else:
> print '-%s' % e,
>
>print '\n'
>
>
More information about the Python-list
mailing list