Reputation: 185
I am implementing a nested for loop which the inner for loop is about looping through combinations. However, I dont understand why this do not work...
import numpy as np
from itertools import combinations
comb = combinations(range(0, 3), 2)
for i in range(0, 2):
for j in comb:
print(i, j)
The output is:
0 (0, 1)
0 (0, 2)
0 (1, 2)
It did not loop the outer loop...however if it is not combination, it works as expected
for i in range(0, 2):
for j in range(0, 2):
print(i, j)
the results are:
0 0
0 1
1 0
1 1
Am i missing some important properties of combinations? I could not figure out why this do not work...sorry if it is a stupid question, any help will be greatly appreciated, thank you.
Upvotes: 1
Views: 91
Reputation: 2182
I think what you are looking for is not combination
, but product
. The below code should work.
from itertools import product
prod = product(range(0, 2), repeat = 2)
for i, j in prod:
print(i, j)
Output:
0 0
0 1
1 0
1 1
Upvotes: 0
Reputation: 8002
You can convert to a list first
from itertools import combinations
comb = list(combinations(range(0, 3), 2))
for i in range(0, 2):
for j in comb:
print(i, j)
Result
0 (0, 1)
0 (0, 2)
0 (1, 2)
1 (0, 1)
1 (0, 2)
1 (1, 2)
Upvotes: 1