Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

list - How to run a i<j loop in Python, and not repeat (j,i) if (i,j) has already been done?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using quite a hacky method just by removing the first element and appending it:

mylist.append(mylist.pop(0))

Where .append(...) will append an element to the end of a list, and .pop(...) will remove an element from a given index and return it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...