gpt4 book ai didi

python - 使用 Python 将字典与列表值组合

转载 作者:IT老高 更新时间:2023-10-28 22:25:17 24 4
gpt4 key购买 nike

我有以下传入值:

variants = {
"debug" : ["on", "off"],
"locale" : ["de_DE", "en_US", "fr_FR"],
...
}

我想处理它们,所以我得到以下结果:

combinations = [
[{"debug":"on"},{"locale":"de_DE"}],
[{"debug":"on"},{"locale":"en_US"}],
[{"debug":"on"},{"locale":"fr_FR"}],
[{"debug":"off"},{"locale":"de_DE"}],
[{"debug":"off"},{"locale":"en_US"}],
[{"debug":"off"},{"locale":"fr_FR"}]
]

这应该适用于字典中任意长度的键。在 Python 中使用 itertools,但没有找到符合这些要求的任何内容。

最佳答案

import itertools as it

varNames = sorted(variants)
combinations = [dict(zip(varNames, prod)) for prod in it.product(*(variants[varName] for varName in varNames))]

嗯,这会返回:

[{'debug': 'on', 'locale': 'de_DE'},
{'debug': 'on', 'locale': 'en_US'},
{'debug': 'on', 'locale': 'fr_FR'},
{'debug': 'off', 'locale': 'de_DE'},
{'debug': 'off', 'locale': 'en_US'},
{'debug': 'off', 'locale': 'fr_FR'}]

这可能不是你想要的。让我适应它...

combinations = [ [ {varName: val} for varName, val in zip(varNames, prod) ] for prod in it.product(*(variants[varName] for varName in varNames))]

现在返回:

[[{'debug': 'on'}, {'locale': 'de_DE'}],
[{'debug': 'on'}, {'locale': 'en_US'}],
[{'debug': 'on'}, {'locale': 'fr_FR'}],
[{'debug': 'off'}, {'locale': 'de_DE'}],
[{'debug': 'off'}, {'locale': 'en_US'}],
[{'debug': 'off'}, {'locale': 'fr_FR'}]]

瞧 ;-)

关于python - 使用 Python 将字典与列表值组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3873654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com