リストの辞書でループを回す
sklearn の GridSearchCV とかって、どうやってループ回してるのか気になったので、調べました。
例として、パラメータ ('A', 'B', 'C') の動く範囲を
d = {'A': [0, 1], 'B': [0, 1, 2], 'C': [0, 1]}
とします。('A', 'B', 'C') は全部で 2 × 3 × 2 = 12 通りの取り方があります。
パラメータ ind in range(12) を用いてそれら12通りを以下の表のように対応させます。
ind | 'A' | 'B' | 'C' |
---|---|---|---|
0 | 0 | 0 | 0 |
1 | 1 | 0 | 0 |
2 | 0 | 1 | 0 |
3 | 1 | 1 | 0 |
4 | 0 | 2 | 0 |
5 | 1 | 2 | 0 |
6 | 0 | 0 | 1 |
7 | 1 | 0 | 1 |
8 | 0 | 1 | 1 |
9 | 1 | 1 | 1 |
10 | 0 | 2 | 1 |
11 | 1 | 2 | 1 |
実装
sample.py
import numpy as np
d = {'A': [0, 1], 'B': [0, 1, 2], 'C': [0, 1]}
keys, values_lists = zip(*d.items())
# keys = ('A', 'B', 'C')
# values_lists = ([0, 1], [0, 1, 2], [0, 1])
sizes = [len(v_list) for v_list in values_lists]
# sizes = [2, 3, 2]
total = np.product(sizes)
# total = 12
for ind in range(12):
out = {}
for key, v_list, n in zip(keys, values_lists, sizes):
ind, offset = divmod(ind, n)
out[key] = v_list[offset]
print(out)
# {'A': 0, 'B': 0, 'C': 0}
# {'A': 1, 'B': 0, 'C': 0}
# ……が、上記の表のように、出力される