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