Unpack a list into indices of another list in python

Can I unpack a list of numbers into a list of indexes? For example, I have lists in a list containing these numbers:

a = [[25,26,1,2,23], [15,16,11,12,10]]

I need to place them in a template, so I did something like this

newA = []

for lst in a:
    new_nums = [lst[4],lst[2],lst[3],lst[0],lst[1]]
    newA.append(new_nums)

print (newA) # prints -->[[23, 1, 2, 25, 26], [10, 11, 12, 15, 16]]

so instead of writing, new_nums = [lst[4],lst[2],lst[3],lst[0],lst[1]]I thought about defining a template as a list with a name pattern = [4,2,3,0,1], and then unpacking them into those indexes lstto create a new order lst.

Is there a great way to do this.

+6
source share
5 answers

Given a list of indexes called pattern, you can use list comprehension like this:

new_lst = [[lst[i] for i in pattern] for lst in a]
+6
source

operator.itemgetter provides a useful display function:

from operator import itemgetter
a = [[25,26,1,2,23], [15,16,11,12,10]]
f = itemgetter(4,2,3,0,1)
print [f(x) for x in a]

[(23, 1, 2, 25, 26), (10, 11, 12, 15, 16)]

list(f(x)), .

+3

numpy, - :

import numpy as np

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

newA = [list(np.array(lst)[pattern]) for lst in a]

, .

+2

In pure Python, you can use list comprehension:

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

newA = []

for lst in a:
    new_nums = [lst[i] for i in pattern]
    newA.append(new_nums)

In numpy, you can use the fancy indexing function:

>>> [np.array(lst)[pattern].tolist() for lst in a]
[[23, 1, 2, 25, 26], [10, 11, 12, 15, 16]]
+2
source

it is slower than the other, but this is another option. you can sort the list by template

a = [[25,26,1,2,23], [15,16,11,12,10]]
pattern = [4,2,3,0,1]
[sorted(line,key=lambda x:pattern.index(line.index(x))) for line in a]
[[23, 1, 2, 25, 26], [10, 11, 12, 15, 16]]
0
source

All Articles