looping over more than one list
Tim Chase
python.list at tim.thechases.com
Thu Feb 16 06:53:15 EST 2006
> def lowest(s1,s2):
> s = ""
> for i in xrange(len(s1)):
> s += lowerChar(s1[i],s2[i])
> return s
>
> this seems unpythonic, compared to something like:
>
> def lowest(s1,s2):
> s = ""
> for c1,c2 in s1,s2:
> s += lowerChar(c1,c2)
> return s
If I understand correctly, something like
for c1,c2 in zip(s1,s2):
is what you're looking for. It will gracefully stop when it
reaches the end of the shortest input. (in your indexed
example above, if s2 is shorter than s1, it will likely
throw an out-of-bounds exception)
For your example, I'd use
def lowest(s1,s2):
return ''.join([lowerChar(c1,c2) for c1,c2 in zip(s1,s2)])
which seems to do what you describe (I understand that
appending to strings is an inefficient operation and is
better done with a join like this)
-tkc
More information about the Python-list
mailing list