I am trying to implement an "i not equal to j" (i<j
) loop, which skips cases where i = j
, but I would further like to make the additional requirement that the loop does not repeat the permutation of (j,i)
, if (i,j)
has already been done (since, due to symmetry, these two cases give the same solution).
First Attempt
In the code to follow, I make the i<j
loop by iterating through the following lists, where the second list is just the first list rolled ahead 1:
mylist = ['a', 'b', 'c']
np.roll(mylist,2).tolist() = ['b', 'c', 'a']
The sequence generated by the code below turns out to not be what I want:
import numpy as np
mylist = ['a', 'b', 'c']
for i in mylist:
for j in np.roll(mylist,2).tolist():
print(i,j)
since it returns a duplicate a a
and has repeated permutations a b
and b a
:
a b
a c
a a
b b
b c
b a
c b
c c
c a
The desired sequence should instead be the pair-wise combinations of the elements in mylist
, since for N=3
elements, there should only be N*(N-1)/2 = 3
pairs to loop through:
a b
a c
b c
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…