Watarap
Watarap

Reputation: 307

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.

Upvotes: 7

Views: 3681

Answers (5)

Mark Tolonen
Mark Tolonen

Reputation: 177554

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.

Upvotes: 3

galaxyan
galaxyan

Reputation: 6111

it is slower than other, but it is another option. you can sort the list based on your pattern

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]]

Upvotes: 0

wim
wim

Reputation: 362557

In pure Python, you can use a 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 may use the fancy indexing feature:

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

Upvotes: 2

Moses Koledoye
Moses Koledoye

Reputation: 78546

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]

Upvotes: 7

Bubble Bubble Bubble Gut
Bubble Bubble Bubble Gut

Reputation: 3358

If you're not opposed to using numpy, then try something like:

import numpy as np

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

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

Hope it helps.

Upvotes: 2

Related Questions