Home > Mobile >  Is there any way to extract a value and its index from a matrix?
Is there any way to extract a value and its index from a matrix?

Time:09-27

I want to extract values from a matrix with their index

For example:

My input is

S = [[1, 2], [4, 8]]

My output should be

{1: (1, 1), 2: (1, 2), 4: (2, 1), 8: (2, 2)}

Is there any way to do this?

CodePudding user response:

Use a dict comprehension:

result = {c: (x, y) for y, r in enumerate(S) for x, c in enumerate(r)}

Output:

{1: (0, 0), 2: (1, 0), 4: (0, 1), 8: (1, 1)}

Note: in Python indexes start from 0, not from 1. If you want to start from 1, use:

result = {c: (x, y) for y, r in enumerate(S, 1) for x, c in enumerate(r, 1)}

Output:

{1: (1, 1), 2: (2, 1), 4: (1, 2), 8: (2, 2)}

CodePudding user response:

Python numbers its indexes from 0, not from one. You seem to be looking for something like this:

result = {}
for y,row in enumerate(S):
    for x,col in enumerate(row):
        result[col] = (x,y)

If there can be duplicates, this gets a little more complicated:

from collections import defaultdict
result = defaultdict(list)
for y,row in enumerate(S):
    for x,col in enumerate(row):
        result[col].append( (x,y) )
  • Related