Iterating over multiple lists (a newbie question)
Alex Martelli
aleaxit at yahoo.com
Fri Jan 5 12:14:47 EST 2001
"Victor Muslin" <victor at prodigy.net> wrote in message
news:3a54d0c5.523585234 at localhost...
[snip]
> 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":
If the situation does not involve command line arguments, its
general case would seem to be:
-- I start with a list of strings, X
-- I would like to make a list of strings, Y,
which is the same as X _except_ that:
-- for certain strings (say those in a set S),
-- if a string in S is found as the non-last
item of X,
-- then I want to make the corresponding
item of Y by "merging" that string in
S with the following one in X
Applied to your example, that would make a list
X=['-port', '10', '-debug'] into another list
Y=['-port 10', '-debug'] (using ' ' as a separator
for the "merging") which you can then parse more
easily. OK, then, one possibility:
def mergeSome(X, S, joiner=' '):
Y=[]
joinnext=0
for x in X:
if joinnext:
Y[-1] += joiner+x
joinnext=0
else:
Y.append(x)
joinnext = x in S
return Y
or, if one prefers to work with indices:
def mergeSome(X, S, joiner=' '):
Y=[]
i=0
while i<len(X)-1:
x = X[i]
if x in S:
Y.append(x+X[i+1])
i += 2
else:
Y.append(x)
i += 1
if i<len(X):
Y.append(X[i])
return Y
Alex
More information about the Python-list
mailing list