给出一本字典,其中包含不同长度的列表,而不仅仅是。
d = {foo: 'hello', bar: [0, 2], baz: [1, 2, 3]}我想创建一个列表,列出所有可能的组合,其中每个组合都是一个字典:
l = [{foo: 'hello', bar: 0, baz: 1},
{foo: 'hello', bar: 0, baz: 2},
{foo: 'hello', bar: 0, baz: 3},
{foo: 'hello', bar: 2, baz: 1},
{foo: 'hello', bar: 2, baz: 2},
{foo: 'hello', bar: 2, baz: 3}]顺序在这里并不重要,我不需要将列表转换回字典。
当然,使用Python循环执行此操作是可能的,但我正在寻找一种更高效和/或更优雅的解决方案。
发布于 2021-07-12 12:59:21
下面的算法以通用的方式回答了这个问题:
def list_of_dictionaries(self, dictionary):
# values which are not lists are forced to be lists
for k, v in dictionary.items():
if type(v) is not list:
dictionary[k] = [v]
# list all combinations of values
combinations = [list(x) for x in dictionary.values() if isinstance(x, list)]
combinations = list(itertools.product(*combinations))
# create list of dictionaries
list_of_dicts = []
for values in combinations:
dict_element = {}
for i, k in enumerate(dictionary.keys()):
dict_element[k] = values[i]
list_of_dicts.append(dict_element)
return list_of_dicts发布于 2021-07-10 13:51:03
Itertools对此很有帮助。代码可能如下所示:
import itertools
d = {'foo': 'hello', 'bar': [0, 2], 'baz': [1, 2, 3]}
a = [list(x) for x in d.values() if isinstance(x, list)]
constant_values = [x for x in d.values() if x not in a]
keys = d.keys()
combinations = list(itertools.product(*a))只需使用constant_values和键将其转换为字典作为最后一步
发布于 2021-07-10 16:36:32
我觉得@DSteman的回答基本上是正确的,他们给了你解决问题所需的工具。
考虑到他们的开场白,我看你在如何完成这件事上陷入困境。因此,这里有一个更简单、更显式的版本,它缺乏它们所包含的灵活性,但直接产生了您所寻求的结果。
如果你觉得这解决了你的问题,我强烈建议你重新考虑他们的答案,并将其视为“解决方案”。
import itertools
data_in = {"foo": "hello", "bar": [0, 2], "baz": [1, 2, 3]}
data_out = [
{"foo": data_in["foo"], "bar": c[0], "baz": c[1]}
for c in itertools.product(data_in["bar"], data_in["baz"])
]
print(data_out)这将产生:
[
{'foo': 'hello', 'bar': 0, 'baz': 1},
{'foo': 'hello', 'bar': 0, 'baz': 2},
{'foo': 'hello', 'bar': 0, 'baz': 3},
{'foo': 'hello', 'bar': 2, 'baz': 1},
{'foo': 'hello', 'bar': 2, 'baz': 2},
{'foo': 'hello', 'bar': 2, 'baz': 3}
]https://stackoverflow.com/questions/68328247
复制相似问题