I have a list of length 6 with L[5] = 3 fixed. I need to loop it around 243 times( or something) to get the combination in a particular order.
The L[4] will keep going 1,2,3 and L[3] would be the same for that time and then it moves right to left. I know it will be some nested loop but can't do it properly. The list can be initialized as anything but L[5] needs to be 3 and the first combination will be L = [1,1,1,1,1,3] and the last combination will be [3,3,3,3,3,3]
CodePudding user response:
IIUC you can use itertools.product
:
from itertools import product
vals = [[1, 2, 3]] * 5 [[3]]
for c in product(*vals):
print(c)
Prints:
(1, 1, 1, 1, 1, 3)
(1, 1, 1, 1, 2, 3)
(1, 1, 1, 1, 3, 3)
(1, 1, 1, 2, 1, 3)
(1, 1, 1, 2, 2, 3)
(1, 1, 1, 2, 3, 3)
(1, 1, 1, 3, 1, 3)
(1, 1, 1, 3, 2, 3)
(1, 1, 1, 3, 3, 3)
(1, 1, 2, 1, 1, 3)
...
(3, 3, 3, 3, 1, 3)
(3, 3, 3, 3, 2, 3)
(3, 3, 3, 3, 3, 3)
CodePudding user response:
Something like this should work:
list = []
for i in range(1,4):
for j in range(1,4):
for k in range(1,4):
for l in range(1,4):
for m in range(3,4):
list.append([i,j,k,l,m])
for elem in list:
print(elem)
Output:
[1, 1, 1, 1, 3]
[1, 1, 1, 2, 3]
[1, 1, 1, 3, 3]
[1, 1, 2, 1, 3]
[1, 1, 2, 2, 3]
[1, 1, 2, 3, 3]
[1, 1, 3, 1, 3]
[1, 1, 3, 2, 3]
[1, 1, 3, 3, 3]
[1, 2, 1, 1, 3]
[1, 2, 1, 2, 3]
[1, 2, 1, 3, 3]
[1, 2, 2, 1, 3]
[1, 2, 2, 2, 3]
[1, 2, 2, 3, 3]
[1, 2, 3, 1, 3]
[1, 2, 3, 2, 3]
[1, 2, 3, 3, 3]
[1, 3, 1, 1, 3]
[1, 3, 1, 2, 3]
[1, 3, 1, 3, 3]
[1, 3, 2, 1, 3]
[1, 3, 2, 2, 3]
[1, 3, 2, 3, 3]
[1, 3, 3, 1, 3]
[1, 3, 3, 2, 3]
[1, 3, 3, 3,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