Iterating over several lists at once
Peter Otten
__peter__ at web.de
Wed Dec 13 09:49:12 EST 2006
Gal Diskin wrote:
> I am writing a code that needs to iterate over 3 lists at the same
> time, i.e something like this:
> for x1 in l1:
> for x2 in l2:
> for x3 in l3:
> print "do something with", x1, x2, x3
> I was wondering if one could write this more easily in some manner
> using only 1 for loop.
def nested_loops(*args):
assert args
if len(args) == 1:
for item in args[0]:
yield (item,)
else:
gap = len(args) // 2
for left in nested_loops(*args[:gap]):
for right in nested_loops(*args[gap:]):
yield left + right
if __name__ == "__main__":
for i, k in nested_loops("abc", "12"):
print i, k
for i, j, k in nested_loops("ab", "123", "xyz"):
print i, j, k
Be prepared for a significant performance hit.
Peter
PS: Did anybody say macro? No? I must be hallucinating...
More information about the Python-list
mailing list