7

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.

Watarap
  • 307
  • 3
  • 11
  • @sapensadler my goal is not to create a flat list, but to retain the lists structure as it is and alter the order of index by passing a custom list of numbers – Watarap Jul 21 '17 at 17:45

5 Answers5

7

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]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
3

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.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
2

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.

2

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]]
wim
  • 338,267
  • 99
  • 616
  • 750
0

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]]
galaxyan
  • 5,944
  • 2
  • 19
  • 43