Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack a List in to Indices of another list in python

Is it possible to unpack a list of numbers in to list indices? For example I have a lists with in a list containing numbers like this:

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

I need to place them in a pattern 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 of defining a pattern as list called pattern = [4,2,3,0,1] and then unpack these in to those indices of lst to create new order of lst.

Is there a fine way to do this.

like image 308
Watarap Avatar asked Jul 21 '17 15:07

Watarap


2 Answers

Given a list of indices called pattern, you can use a list comprehension like so:

new_lst = [[lst[i] for i in pattern] for lst in a]
like image 63
Moses Koledoye Avatar answered Sep 29 '22 15:09

Moses Koledoye


operator.itemgetter provides a useful mapping 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)]

Use list(f(x)) if you want list-of-lists instead of list-of-tuples.

like image 25
Mark Tolonen Avatar answered Sep 29 '22 16:09

Mark Tolonen