简体   繁体   中英

Find position on a matrix and retrieve the value of that position, based on characters on a string Python

I have a file that can be considered a database or a distance matrix. Right now the file is.cnv.

    J    A    Z    B
J   0    1    3    2
A   1    0    7    3
Z   3    7    0    1
B   2    3    1    0

And another file with strings of characters.

JBZAJJZA
BBAJJZAB

Now I want to be able to get, from the matrix or database, the value associated to the characters being compared at a position. For example, for the first character of each string, JxB is supposed to be 2, according to the matrix. How do I write that I want that number?

So far all of my attempts resulted in me rewriting the matrix on the script, instead of using the file of the matrix.

My thoughts are: find at the first row the character that match the character of the first string, find at the first column the character of the second string, and then give the value of the position Char1 x Char2. But I couldn't find a way to do this.

I am using python. I didn't assign a datatype to the matrix yet.

If you read this and have any ideas/suggestions, thank you:)

You need to find a way to load your data in python, that will make things a lot easier. Then you can create a map that maps the characters to indices: For example:

map = {"J": 0, "A": 1, "Z":2 , "B":3}

Then if you have two strings and lets say a numpy array m containing your matrix you can do:

str_a = "JBZAJJZA"
str_b = "BBAJJZAB"

for char_i in str_a:
    for char_j in str_b:
        v = m[map[char_i], map[char_j]]
        print(m)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM