Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get a permutation given indexes?

I've got a list of objects:

array = [object0,object1,object2,object3,object4]

and i want to change the order of the items given a permutation:

permutation = [ 2 , 4 , 0 , 1 , 3 ]

Is there a command in python that will do something like:

result = Permute(array,permutation)

result = [object2,object4,object0,object1,object3]

I know i can do it with a simple for loop....

like image 358
Yochai Timmer Avatar asked Dec 07 '22 20:12

Yochai Timmer


2 Answers

If we are assuming that permutation is a proper permutation of 0-n (each appears exactly once), then the following code should work:

result=[array[i] for i in permutation]
like image 142
murgatroid99 Avatar answered Dec 24 '22 14:12

murgatroid99


In Python, this is easy to do with a list comprehension:

result = [array[i] for i in permutation]
like image 20
John Bartholomew Avatar answered Dec 24 '22 16:12

John Bartholomew