简体   繁体   English

根据字符串 Python 中的字符,在矩阵上查找 position 并检索该 position 的值

[英]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.现在文件是.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.现在我希望能够从矩阵或数据库中获取与在 position 处进行比较的字符关联的值。例如,根据矩阵,对于每个字符串的第一个字符,JxB 应该为 2。 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.我的想法是:在第一行找到与第一个字符串的字符匹配的字符,在第一列找到第二个字符串的字符,然后给出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.我正在使用 python。我还没有为矩阵分配数据类型。

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.你需要找到一种方法来加载 python 中的数据,这将使事情变得容易得多。 Then you can create a map that maps the characters to indices: For example:然后你可以创建一个 map 将字符映射到索引:例如:

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:然后,如果您有两个字符串,假设一个 numpy 数组 m 包含您的矩阵,您可以执行以下操作:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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