使用 Python 将字典与列表值进行组合
我有以下传入值:
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,但没有找到任何符合这些要求的东西。
I have the following incoming value:
variants = {
"debug" : ["on", "off"],
"locale" : ["de_DE", "en_US", "fr_FR"],
...
}
I want to process them so I get the following result:
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"}]
]
This should work with arbitrary length of keys in the dictionary. Played with itertools in Python, but did not found anything matching these requirements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
嗯,这返回:
这可能不完全是您想要的。让我调整它...
现在返回:
Voilà ;-)
Hm, this returns:
which is probably not exactly, what you want. Let me adapt it...
returns now:
Voilà ;-)
这就是我使用的:
适用于您的示例给出:
我发现这比上面的一行更具可读性。
此外,它还返回一个像
itertools.product
这样的迭代器,因此它让用户自行决定是实例化列表还是一次只使用一个值。This is what I use:
which applied to your example gives:
I find this is more readable than the one liners above.
Also, it returns an iterator like
itertools.product
so it leaves it up to the user whether to instantiate a list or just consume the values one at a time.我假设你想要所有键的笛卡尔积?因此,如果您有另一个条目“foo”,其值为 [1, 2, 3],那么您总共会有 18 个条目?
首先,将值放入列表中,其中每个条目都是该位置可能的变体之一。在您的情况下,我们想要:
为此:
接下来我们可以使用笛卡尔积函数来扩展它...
请注意,这不会复制字典,因此所有
{'debug': 'on'}
字典是相同的。I assume you want the cartesian product of all the keys? So if you had another entry, "foo", with values [1, 2, 3], then you'd have 18 total entries?
First, put the values in a list, where each entry is one of the possible variants in that spot. In your case, we want:
To do that:
Next we can use a Cartesian product function to expand it...
Note that this doesn't copy the dicts, so all the
{'debug': 'on'}
dicts are the same.