In Python 2.5:

import itertools def combinations(*seqs): def base_combinations(so_far, seq): for x in seq: yield so_far + [x] def nested_combinations(so_far, seqs): if len(seqs) == 1: return base_combinations(so_far, seqs[0]) else: iterators = (nested_combinations(so_far + [x], seqs[1:]) for x in seqs[0]) return itertools.chain(*iterators) return nested_combinations([], seqs)

Usage:

for x, y, z in combinations(xs, ys, zs): # Perform magic

If you have a better way, I’d like to read it.

(Thanks to Colin for inspiring me to write it, and renaming one of the nested functions.)

Categories: Programming; Python. | Comments: 27 (feed). | Trackback.