Search code examples
pythonlistdictionarymultidimensional-arraycoordinates

Python 2D List Conditional Mapping from Multiple 2D Lists


I have a list of lists A that looks like this

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

Then I have two other list of lists B and C that looks as below:

B = [['a', 'c', 's'],
     ['y', 'e', 's'],
     ['u', 'w', 'g']]

C = [['i', 'p', 'u'],
     ['k', 'l', 'n'],
     ['h', 'o', 'm']]

I am trying to perform mapping from A to B and C, with value conditioning:

When the 'cell' value is 1, refer to the value at the same position in B, and likewise refer to C when it is 0.

I tried to break down the problem by trying to map list to lists. But it seems to lead to nowhere.

How can I map A to B and C so that it results in a list of lists like this?

[['a', 'p', 'u'],   # 'a' from B; 'p' from C; 'u' from C
 ['y', 'e', 's'],   # 'y' from B; 'e' from B; 's' from B
 ['h', 'w', 'm']]   # 'h' from C; 'w' from B; 'm' from C

Solution

  • You can iterate over the 3 lists together by zipping them first:

    [[a and b or c for a, b, c in zip(*t)] for t in zip(A, B, C)]
    

    Demo: https://ideone.com/f8XRdk