Pythonで直積を求めるには、Python2.6で導入されたitertools.productを使う。
from itertools import product
Python2.5以前では、ドキュメントに示されているitertools.productと等価の以下のコードを使う。
def product(*args, **kwds):
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
簡単な例
>>> for i in product(('a','b','c'), ('X','Y'), ('1','2')):
... print i
...
('a', 'X', '1')
('a', 'X', '2')
('a', 'Y', '1')
('a', 'Y', '2')
('b', 'X', '1')
('b', 'X', '2')
('b', 'Y', '1')
('b', 'Y', '2')
('c', 'X', '1')
('c', 'X', '2')
('c', 'Y', '1')
('c', 'Y', '2')
引数のイテラブルが同じ時はrepeatで繰り返し回数を指定できる。
「product((‘1′,’2’), repeat=3)」は「product((‘1′,’2’), (‘1′,’2’), (‘1′,’2’))」と同じ。
>>> for i in product(('1','2'), repeat=3):
... print i
...
('1', '1', '1')
('1', '1', '2')
('1', '2', '1')
('1', '2', '2')
('2', '1', '1')
('2', '1', '2')
('2', '2', '1')
('2', '2', '2')