create specific permutation of a list in python

1.8k Views Asked by At

I'm trying to write a function that would input a list (of pre-determined length) and output the permutation of that list according to my choice of re-ordering.

For example, suppose I have the list

    [1,'a',12,'b','poppy']

and I have the permutation

    (3,4,5,2,1)

Then the function output would be a list with the third element first, the fourth element second, etc

    [12,'b','poppy','a',1]
3

There are 3 best solutions below

9
On BEST ANSWER
l = [1,'a',12,'b','poppy']

def p(l,t):
    return [l[i-1] for i in t]

print(p(l,(3,4,5,2,1)))
[12, 'b', 'poppy', 'a', 1]

indexing is 0 based so if you actually wanted to use the indexes for a 5 element list it would be (2,3,4,1,0) and [l[i] for i in t]

0
On

The first element of the list is 0:

l = [1,'a',12,'b','poppy']
p = (2,3,4,1,0)
result = []
for i in p:
    result.append(l[i])
1
On

Use operator.itemgetter. Since your permutations are for a 1-based list, you'll need to add a dummy element to the front of your list first. (You could subtract one from each element of p using a variety of techniques, but it's simpler to just "shift" the list before passing it to the function returned by itemgetter.)

>>> from operator import itemgetter
>>> p = (3,4,5,2,1)
>>> lst = [1,'a',12,'b','poppy']
>>> itemgetter(*p)([None] + lst)
(12, 'b', 'poppy', 'a', 1)