0

my list is as fallows

dg = [[[a1,b1], [a1,b1]],[[a2,b2], [a2,b2]], [[a3,b3], [a3,b3]],[[a4,b4], [a4,b4]]]

I want to create a function that swaps specific elements within the nested list. For example, something that swaps the first b1 with the first b3, creating the new list of

dg = [[[a1,b3], [a1,b1]],[[a2,b2], [a2,b2]], [[a3,b1], [a3,b3]],[[a4,b4], [a4,b4]]]

I am working in python.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
Asiv
  • 115
  • 6

1 Answers1

1

Use tuple unpacking to swap elements - as described more detailed in this answer

With a nested list it's basically the same, you just have to reference the position.

A = [[['a1','b1'], ['a1','b1']],[['a2','b2'], ['a2','b2']], 
     [['a3','b3'], ['a3','b3']],[['a4','b4'], ['a4','b4']]]


A[0][0][1], A[2][0][1] = A[2][0][1], A[0][0][1]

>>> A
[[['a1', 'b3'], ['a1', 'b1']], [['a2', 'b2'], ['a2', 'b2']], 
 [['a3', 'b1'], ['a3', 'b3']], [['a4', 'b4'], ['a4', 'b4']]]

If you find all the brackets hard to read you could use a numpy array

import numpy as np
B = np.array(A)
B[0,0,1], B[2,0,1] = B[2,0,1], B[0,0,1]

To wrap it in a simple function:

def arr_swap(arr, idx1, idx2):
    arr[idx1], arr[idx2] = arr[idx2], arr[idx1]

Just ensure you call it with tuples as index values

arr_swap(B, (0,0,1), (2,0,1))
NLindros
  • 1,683
  • 15
  • 15