0

The list A is based on list T1. Now T1 is transformed to list T2. I want to replace the index numbers of list A with respect to T2 i.e. element 1 is to be replaced with 2, 2 is to be replaced with 4, 3 is to be replaced with 5. I present the expected output.

import numpy as np

T1 = [0, 1, 2, 3, 4, 5, 6, 7]
A=[np.array([[[0, 1],
        [0, 3],
        [1, 3],
        [3, 4],
        [3, 6],
        [4, 5],
        [4, 7],
        [5, 7],
        [6, 4]]])]

T2 = [0, 2, 4, 5, 8, 9, 10, 11]

The expected output is

A=[array([[[0, 2],
        [0, 5],
        [2, 5],
        [5, 8],
        [5, 10],
        [8, 9],
        [8, 11],
        [9, 11],
        [10, 8]]])]
Trier123
  • 3
  • 2
  • Welcome to Stack Overflow. Let me make sure I understand the problem correctly. The idea is: because `T2` has the value `2` in the same position where `T1` has the value `1`, therefore every `1` in the `A` array should be replaced with `2`? – Karl Knechtel Aug 27 '22 at 12:17
  • Does https://stackoverflow.com/questions/14448763 answer your question? – Karl Knechtel Aug 27 '22 at 12:18
  • That's right. Basically, there's one-to-one correspondence between ```T1``` and ```T2``` i.e. all ```1``` is to be replaced with ```2```, all ```2``` to be replaced with ```4``` and so on... – Trier123 Aug 27 '22 at 12:20

2 Answers2

0

The following code should work for any arrays T1, T2 and A, where T1 and T2 have the same length and any value in A can be found in T1. First we create a dictionary where each value in T1 is mapped to the value at the same index in T2. After that we replace all the values in A with the ones they map to.

def general(T1, T2, A):
    tmp = A[0][0]
    map = dict(zip(T1, T2))

    for i in range(0, len(tmp)):
        pair = tmp[i]
        pair[0] = map[pair[0]]
        pair[1] = map[pair[1]]
    return A

For the specific example it is not necessary to create the dictionary. Since T1 already contains the index of the value to use in T2, we can replace the values in A directly.

def specific(T2, A):
    tmp = A[0][0]
    for i in range(0, len(tmp)):
        pair = tmp[i]
        pair[0] = T2[pair[0]]
        pair[1] = T2[pair[1]]
    return A
Johann Schwarze
  • 161
  • 1
  • 4
0
zip_dict = dict(zip(T1, T2))
B = [np.array([[list(map(lambda x: zip_dict[x],list(i))) for i in A[0][0]]])]
SimoN SavioR
  • 614
  • 4
  • 6