【发布时间】:2016-05-07 20:49:57
【问题描述】:
我正在编写一个 python 脚本,其中我有多个 for 循环,除了嵌套在其中的 for 循环的数量之外,它们都是相同的。
让我告诉你我的意思:
#4 & 1
for a1 in someList:
for a2 in someList:
for a3 in someList:
for a4 in someList:
for b1 in anotherList:
resultList.append((a1 + a2 + a3 + a4) - b1);
#3 & 1
for a1 in someList:
for a2 in someList:
for a3 in someList:
for b1 in anotherList:
resultList.append((a1 + a2 + a3) - b1);
#2 & 1
for a1 in someList:
for a2 in someList:
for b1 in anotherList:
resultList.append((a1 + a2) - b1);
#2 & 2
for a1 in someList:
for a2 in someList:
for b1 in anotherList:
for b2 in anotherList:
resultList.append((a1 + a2) - (b1 + b2));
请记住,这只是演示问题的示例。我正在处理的实际数据不是数字,而且每次迭代我都会执行更多操作。
好的,现在问题来了:
如何将所有这些代码放入一个不错的函数中,以便我可以执行以下操作:
myFunc(4, 1);
myFunc(3, 1);
myFunc(2, 1);
myFunc(2, 2);
如果你们能回答这个问题,这对我来说将是一个巨大的帮助。我没有足够的创造力来独自解决这个难题。 :(
另外,如果答案已经存在,很抱歉发布这个问题 - 我不知道这个东西叫什么,所以我不知道要搜索什么。
提前致谢! ~下午
更新: 谢谢大家的帮助。我认为这会奏效。你们都非常有帮助!
【问题讨论】:
-
为什么会有这些五重嵌套的
for循环?听起来你在暴力破解你真的不应该做的事情,要么是因为有更快的方法可以做到这一点,要么是因为这是一个非常困难的问题,你应该引入一个已建立的库。
标签: python loops for-loop nested