说明
- 我需要把一个dict,它的值是一个列表,分解成几个dict,保留其他部分李>
- 我想要断开的键可能有不同的名称,但是
cond
只会得到一个类型为list
的值李>
示例
cond = {"type":"image","questionType":["3","4","5"]}
cond = {"type":"example","fieldToBreak":["1","2","3"],"fieldInt":1,"fieldFloat":0.1}
[
{'type': 'image', 'questionType': '3'},
{'type': 'image', 'questionType': '4'},
{'type': 'image', 'questionType': '5'}
]
[
{'type': 'example', 'fieldToBreak': '1', 'fieldInt': 1, 'fieldFloat': 0.1},
{'type': 'example', 'fieldToBreak': '2', 'fieldInt': 1, 'fieldFloat': 0.1},
{'type': 'example', 'fieldToBreak': '3', 'fieldInt': 1, 'fieldFloat': 0.1}
]
我所尝试的
cond_queue = []
for k,v in cond.items():
if isinstance(v,list):
for ele in v:
cond_copy = cond.copy()
cond_copy[k] = ele
cond_queue.append(cond_copy)
break
- 它是有效的,但我认为它不是最好的pythonic解决方案李>
问题:
Tags:
利用python内置函数和标准库的可能方法。该代码可以与任意数量的键一起使用。在原始目录中出现多个列表的情况下,它会创建值元素的所有组合。不确定此逻辑是否正确
输出:
除了输入字典之外,这个小函数不需要任何额外的参数就可以完成这项工作
函数确定列表项中有多少项(
n
),并使用该信息提取要插入字典的正确值。在n
(for i in range(n):
)上循环用于在最终输出中追加正确数量的词典。就这样。很容易阅读和理解类似于下面的内容(解决方案基于帖子的输入,我假设它代表了一般情况)
输出
相关问题 更多 >
编程相关推荐