0

I have an array like this:

a = [[ 8, 7, 6, 5, 9],
     [1, 2, 1, 6, 4],
     [4, 2, 5, 4, 2]]`

I want to change the order of that array based on second row with an order like this: b = [2, 6, 1, 1, 4]

So, I want the result becomes like this:

a = [[7, 5, 8, 6, 9],
     [2, 6, 1, 1, 4],
     [2, 4, 4, 5, 2]]

How can I solve this problem in Python?

new Q Open Wid
  • 2,225
  • 2
  • 18
  • 34

2 Answers2

0
a = [[ 8, 7, 6, 5, 9],
    [1, 2, 1, 6, 4],
    [4, 2, 5, 4, 2]]
a[1] = [2, 6, 1, 1, 4]

Try that.

0

In this answer, I'm making the following two assumptions:

  • All sub-lists are 5 elements in length
  • The desired logic is to move the 2nd and 4th elements to be 1st and 2nd respectively

If both of the assumptions made above are true, you can use list comprehension on a nested list, and create a list to specify how the lists should be reordered.

a = [[8, 7, 6, 5, 9],
     [1, 2, 1, 6, 4],
     [4, 2, 5, 4, 2]]

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

b = [[l[i] for i in new_ord] for l in a]
print(b) #prints: [[7, 5, 8, 6, 9], [2, 6, 1, 1, 4], [2, 4, 4, 5, 2]]
tarheel
  • 4,727
  • 9
  • 39
  • 52
  • Thanks for helping. Suppose that now I have a different order on b list, could you please help me on how to create a new_order list? since I have an identical value in that list (1). – kututaji Apr 27 '20 at 05:11
  • @kututaji Not sure what you mean. May need some clarification in the question, or a separate question. – tarheel Apr 27 '20 at 23:49