达令说
import itertools>>> for i in itertools.product([1,2,3],['a','b'],[4,5]):... print i...(1, 'a', 4)(1, 'a', 5)(1, 'b', 4)(1, 'b', 5)(2, 'a', 4)(2, 'a', 5)(2, 'b', 4)(2, 'b', 5)(3, 'a', 4)(3, 'a', 5)(3, 'b', 4)(3, 'b', 5)>>>
蝴蝶不菲
对于Python 2.5及更早版本:>>> [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]][(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), (3, 'b', 4), (3, 'b', 5)]这是一个递归版本product()(只是一个插图):def product(*args): if not args: return iter(((),)) # yield tuple() return (items + (item,) for items in product(*args[:-1]) for item in args[-1])例:>>> list(product([1,2,3], ['a','b'], [4,5])) [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), (3, 'b', 4), (3, 'b', 5)]>>> list(product([1,2,3]))[(1,), (2,), (3,)]>>> list(product([]))[]>>> list(product())[()]