问题描述
这链接到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_config': {'AtariEnv': {'game': 'pong'}}})
('A2C','env_config': {'AtariEnv': {'game': 'breakout'}}})
('A2C','env_config': {'AtariEnv': {'game': 'pong'}}})
('DQN','env_config': {'AtariEnv': {'game': 'breakout'}}})
('DQN','env_config': {'AtariEnv': {'game': 'pong'}}})
************************
('PPO','env_config': {'AtariEnv': {'game': 'pong'}}})
请注意 product
中的打印语句如何正常工作,而 yield
中的打印失败并且不会改变后面配置的 env
值。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)