我有一个python字典,其中每个条目的值要么是一个列表,要么是另一个条目也是列表的字典。我想创建一个python迭代器,它遍历字典中所有可能的状态,其中每个键处的列表定义了该键的可能值。你知道吗
我尝试遍历每个键,并在列表中找到下一个元素作为值,但这只涵盖了一些组合。这是因为一旦一个列表耗尽,您需要重置为第一个值并移动到下一个列表。你知道吗
如果我们把这句话交给迭代器。。。你知道吗
{
"key0": {
"key1": [1, 2],
"key2": [8, 9, 10]
}
"key3": [22, 23, 24]
}
它应该产生的第一个迭代是。。。你知道吗
{
"key0": {
"key1": 1,
"key2": 8
}
"key3": 22
}
第二个是。。。你知道吗
{
"key0": {
"key1": 2,
"key2": 8
}
"key3": 22
}
第三个是。。。 (注意key1是如何返回到1的)
{
"key0": {
"key1": 1,
"key2": 9
}
"key3": 22
}
预期结果是迭代字典的每个可能状态(总共18个),其中每个键处的列表定义该键的可能值。你知道吗
以下是我的解决方案:
在执行了以下测试之后,我得到了您所说的结果
以下是使用
itertools.product
和递归的简明方法:运行示例:
字典不是有序结构,您不应该尝试对其进行迭代。但是,如果必须这样做,方法可以是:
用你想要的任何功能替换指纹,你应该没事!如果您有嵌套的字典或列表,请记住这些值就是(在您的示例中)字典或列表,从那里,您可以以类似的方式在循环中操纵它们。你知道吗
这应该管用
相关问题 更多 >
编程相关推荐