Home > OS >  Swapping two elements in a list of lists of lists in Python
Swapping two elements in a list of lists of lists in Python

Time:03-15

I have a list of lists in Python where all the sub-lists are pairs.

For example, if there is a pair of ['b', 'c'], there would be a pair of ['c', 'b'], as well.

 mylist = [[['a', 'c'], ['e', 'f'], ['b', 'd']],
 [['a', 'd'], ['f', 'b'], ['c', 'e']],
 [['a', 'e'], ['b', 'c'], ['d', 'f']],
 [['a', 'b'], ['d', 'e'], ['f', 'c']],
 [['a', 'f'], ['c', 'd'], ['e', 'b']],
 [['c', 'a'], ['f', 'e'], ['d', 'b']],
 [['d', 'a'], ['f', 'b'], ['e', 'c']],
 [['b', 'a'], ['e', 'd'], ['c', 'f']],
 [['f', 'a'], ['e', 'c'], ['b', 'e']],
 [['e', 'a'], ['c', 'b'], ['f', 'd']]]

I want to randomly chose a pair and exchange it with the reversed pair. So, where ['a', 'b'] is , I want to replace it with ['b', 'a'], and vice versa.

Then, mylist would be:

 mylist = [[['a', 'c'], ['e', 'f'], ['b', 'd']],
     [['a', 'd'], ['f', 'b'], ['c', 'e']],
     [['a', 'e'], ['b', 'c'], ['d', 'f']],
     [['b', 'a'], ['d', 'e'], ['f', 'c']],
     [['a', 'f'], ['c', 'd'], ['e', 'b']],
     [['c', 'a'], ['f', 'e'], ['d', 'b']],
     [['d', 'a'], ['f', 'b'], ['e', 'c']],
     [['a', 'v'], ['e', 'd'], ['c', 'f']],
     [['f', 'a'], ['e', 'c'], ['b', 'e']],
     [['e', 'a'], ['c', 'b'], ['f', 'd']]]

I randomly pick the pair with:

randomnumber1 = random.randint(0,len(mylist))
randomnumber2 = random.randint(0,int(mylist/2))

for index, round in enumerate(mylist):
    for idx, couple in enumerate(round):
        if index==randomnumber1 and idx==randomnumber2:
            picked = couple
            reversedpair = list(reversed(picked))

So far, so good, I found the pairs that I want to exchange, but how can I proceed with the exchange?

I want to incorporate this solution, but the difference is that this is a list of lists.

CodePudding user response:

You should randomly select a row and column, then iterate over the rows and columns to find the indices of the corresponding element to swap with. Once these indices have been found, you can perform a swap operation as normal:

selected_row = random.randint(0, len(mylist) - 1)
selected_col = random.randint(0, len(mylist[0]) - 1)

for row in range(len(mylist)):
    for col in range(len(mylist[0])):
        if mylist[selected_row][selected_col] == mylist[row][col][::-1]:
            mylist[selected_row][selected_col], mylist[row][col] = \
                mylist[row][col], mylist[selected_row][selected_col]
            break

CodePudding user response:

here is one way , keep the randomly selected value in a variable and try to find matches, then reverse each match:

selected = mylist[randomnumber1][randomnumber2]
for i, sublist in enumerate(mylist):
    for j, item in enumerate(sublist):
        if item in (selected ,selected[::-1]):
            mylist[i][j] = mylist[i][j][::-1]

print(mylist)
  • Related