productについて
from itertools import product
を使用すればfor文の多重ループをまとめて1行にすることができます。
これを利用すると
for a in A: for b in B: for c in C: for d in D:
の4重ループは
for a, b, c, d in product(A, B, C, D):
とすることができます。
2重ループの場合
サンプル1(rangeでループ)
from itertools import product for i, j in product(range(2), range(3)): print(f'{i} : {j}')
実行結果
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 1, j = 0 i = 1, j = 1 i = 1, j = 2
サンプル2(listでループ)
from itertools import product I = ['A', 'B', 'C'] J = ['X', 'Y'] for i, j in product(I, J): print(f'i = {i}, j = {j}')
実行結果
i = A, j = X i = A, j = Y i = B, j = X i = B, j = Y i = C, j = X i = C, j = Y
3重ループの場合
from itertools import product A = range(2) B = range(3) C = range(2) for a, b, c in product(A, B, C): print(f'a = {a}, b = {b}, c = {c}')
実行結果
a = 0, b = 0, c = 0 a = 0, b = 0, c = 1 a = 0, b = 1, c = 0 a = 0, b = 1, c = 1 a = 0, b = 2, c = 0 a = 0, b = 2, c = 1 a = 1, b = 0, c = 0 a = 1, b = 0, c = 1 a = 1, b = 1, c = 0 a = 1, b = 1, c = 1 a = 1, b = 2, c = 0 a = 1, b = 2, c = 1