swapping values in a list while looping through it.

Asked by JD

Hi guys,

I have a list
List=[a,b,c,d,e,f,g,h]

and i want to swap values in turn:
eg:

1.st modification = [b,a,c,d,e,f,g,h]
2nd modification=[a,c,b,d,e,f,g,h]
3rd modification =[a,b,d,c,e,f,g,h]
etc...

ideally I would actually like to create a new list that is:
new_List=[[b,a,c,d,e,f,g,h],[a,c,b,d,e,f,g,h],[a,b,d,c,e,f,g,h]]

I am using the following method to swap them:

Temp=List[1]
List1=List[2]
List[2]=Temp

which works fine, however when I loop through the list it doesn't revert back to the original list since the values have now been swapped. Effectively it continues to swap the already swapped list. (I think the solution might lie in shallow copy versus deep copy, i tried using a 'placeholder' for the list with placeholder=list[:], but I can't figure it out. Any suggestions?

Thank you for the help, I am slowly (very very slowly) getting the hang of things

Question information

Language:
English Edit question
Status:
Answered
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
RaiMan (raimund-hocke) said :
#1

if you do not really need the permutations permanently, but only inside a loop, you might do the swap, do your job and simply swap back.

an example

r = [1,2,3,4,5,6,7,8]
r1 = []
for i in range(len(r)-1):
    r1.append((i+1,i))
print r1 # this is the swapping directive

for i in r1:
    (r[i[0]], r[i[1]]) = (r[i[1]], r[i[0]]) #swaps according to rule i
    print r # here goes your processing
    (r[i[1]], r[i[0]]) = (r[i[0]], r[i[1]]) #swaps back according to rule i

Revision history for this message
JD (keelbo) said :
#2

That works, thanks for that. r1 in my case is around 60 indexes long, is it normal for Sikuli to take just over 10 seconds to do this processing then?

Revision history for this message
RaiMan (raimund-hocke) said :
#3

if you are running the above loop with the print, it is the print, that is rather slow for a list of 60 entries.

The list processing as such is very fast (just try without the print ;-)

Can you help with this problem?

Provide an answer of your own, or ask JD for more information if necessary.

To post a message you must log in.