【发布时间】:2018-11-11 08:09:27
【问题描述】:
我有一个问题,随着问题的发展,这有点问题。
情况:
我需要将可变大小的列表中的项目与可变大小的元素组合在一起,存储这些组合,然后遍历它们。我尝试了 itertools,但我得到了太多的组合,我不知道如何正确“清理”。 通过创建与输入列表中“op”元素的数量一样多的 for 循环,我得到了正确的组合。
示例: 注意:“op”字典的数量可能会有所不同!忽略这样的值,重要的是,我使用“op”字典列表来基本上获取 Nuke GUI 元素中称为 NoOp 节点的所有自定义控件。我需要遍历每个值的每个控件,进行所有可能的组合:
for option1 in op1["options"]:
for option2 in op2["options"]:
for option3 in op3["options"]:
print op1["control"], option1, op2["control"], option2, op3["control"], option3
现在我只是想弄清楚如何定义基本情况:/
def getCombos(controls, n = 0):
#combos = []
if n == 0:
#return [(control["control"], option) for control in controls for option in control["options"]]
return [(item["control"], option) for item in controls for option in item["options"]]
else:
for control in controls:
return(getCombos(controls, n-1))
n -= 1
op1 = {"control": "Material", "options": ["Glass", "Metal", "Wood"]}
op2 = {"control": "Base",
"options": ["Chrome", "Brass", "Bronce", "Gold", "Nickel", "Red Gold"]}
op3 = {"control": "Color", "options": ["Red", "Blue", "Green", "Cyan", "SomeWonderfulNewColor"]}
controls = [op1, op2, op3]
#NOTE: number of elements (dict) in list controls may vary!
for i,combo in enumerate(getCombos(controls, n=len(controls))):
print i, combo
ATM 这个脚本只是递归地打印控件
在这种情况下如何使用递归,更重要的是,我应该使用递归吗?如果是,我该如何处理这种情况并将其分解为组件? 干杯,
【问题讨论】:
-
虽然我喜欢介绍,但帖子缺少带有具体示例数据的minimal reproducible example。当前方法的输入、预期输出和错误输出。
-
你想要什么样的“组合”?你试过
itertools.product(opt1["options"], opt2["options"], ...)吗? -
也许我真的应该把元组放在前面的例子中:for option1 in op1["options"]: for option2 in op2["options"]: for option3 in op3["options"]: print ( op1["control"], option1), (op2["control"], option2), (op3["control"], option3) 我会尝试已经发布的解决方案,干杯
标签: python loops for-loop recursion iteration