【发布时间】:2021-09-05 01:30:50
【问题描述】:
这是链接到Cartesian product of nested dictionaries of lists
假设我有一个嵌套字典,其中包含表示多个配置的列表,例如:
{'algorithm': ['PPO', 'A2C', 'DQN'],
'env_config': {'env': 'GymEnvWrapper-Atari',
'env_config': {'AtariEnv': {'game': ['breakout', 'pong']}}}
目标是计算嵌套字典中列表的笛卡尔积以获得所有可能的配置。
这是我目前得到的:
def product(*args, repeat=1, root=False):
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
print("************************")
print(root)
for r in result:
print(tuple(r))
print("************************")
for prod in result:
yield tuple(prod)
def recursive_cartesian_product(dic, root=True):
# based on https://stackoverflow.com/a/50606871/11051330
# added differentiation between list and entry to protect strings in dicts
# with uneven depth
keys, values = dic.keys(), dic.values()
vals = (recursive_cartesian_product(v, False) if isinstance(v, dict)
else v if isinstance(v, list) else (v,) for v in
values)
print("!", root)
for conf in product(*vals, root=root):
print(conf)
yield dict(zip(keys, conf))
这是相关的输出:
************************
True
('PPO', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'breakout'}}})
('PPO', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
('A2C', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'breakout'}}})
('A2C', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
('DQN', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'breakout'}}})
('DQN', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
************************
('PPO', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'breakout'}}})
('PPO', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
('A2C', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
('A2C', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
('DQN', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
('DQN', {'env': 'GymEnvWrapper-Atari', 'env_config': {'AtariEnv': {'game': 'pong'}}})
请注意product 中的打印语句如何正常工作,而yield 中的打印失败并且不会改变以后配置的env 值。
【问题讨论】:
标签: python recursion generator cartesian