【发布时间】:2014-05-02 11:35:22
【问题描述】:
我想根据用户决定使用的数字创建一个组合求解器,并为第一个循环中的每个项目获取其余循环的所有组合,例如:
intNumberOfLoops = 3
lstLoopOne = ['loop01item01', 'loop01item02', 'loop01item03', 'loop01item04', 'loop0item05']
#Since we will be getting all combinations in relation to lstLoopOne, we will always need at #least one loop and thus we subtract it from intNumberOfLoops
if intNumberOfLoops < 2:
print("Gotta put in more than 2 loops")
exit()
for i in range(intNumberOfLoops-1):
#create loops and same number of items as lstLoopOne dynamically for example:
lstLoopTwo = ['loop02item01', 'loop02item02', 'loop02item03', 'loop0item04', 'loop0item05']
lstLoopThree = ['loop03item01', 'loop03item02', 'loop03item03', 'loop03item04', 'loop03item05']
#since we dont know how many loops the user wants to use at design-time, maybe we would have to use a list for lists??? But how would we get the list names which are based on the loop number and put it into a list of lists?
#then run itertools.combinations on every item in the list of lists for example:
for w in lstOfLists:
#dynamicvariable = w.itertools.combinations
#for every dynamic variable that was created by previod for:
print(#all loop combinations in this case it would be for three loops:
#loop01item01, loop02item01, loop03item01 <-iteration 01
#loop01item01, loop02item01, loop03item02 <-iteration 02
#loop01item01, loop02item01, loop03item03 <-iteration 03
#loop01item01, loop02item01, loop03item04 <-iteration 04
#loop01item01, loop02item01, loop03item05 <-iteration 05
...
#loop01item01, loop02item02, loop03item01 <-iteration n
#loop01item01, loop02item02, loop03item02 <-iteration n+1
...
#loop01item02, loop02item01, loop03item01 <-iteration t
#loop01item02, loop02item01, loop03item02 <-iteration t+1
#loop01item02, loop02item01, loop03item03 <-iteration t+2
...
#loop01item02, loop02item02, loop03item01 <-iteration s
#loop01item02, loop02item02, loop03item02 <-iteration s+1
...
【问题讨论】:
-
也许你可以使用
itertools.product(),那么它会是:for i,j,k,l,m,n in product(lst, lst, lst, lst, lst, lst),而且你不必更深入地处理你的for循环...... -
非常感谢 Sharath
标签: python loops iteration combinations