在Python中比较两个列表的有效方法(从R代码转换)

2024-06-26 18:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为基因组数据编写一个转换矩阵计算器。我有两个单核苷酸多态性列表:previousStatecurrentState。我的文件中还有一个独特的核苷酸列表:uniqueSNPs

我正在尝试转换R中的嵌套for循环:

for (i in 1 : nstate) { totalNucleotides = sum(previousState == uniqueSNPs[i]) for (j in 1 : nstate) { matches = sum(previousState == uniqueSNPs[i] & previousState == uniqueSNPs[j]) tran.mat[i, j] = matches / totalNucleotides } }

其中nstate就是uniqueSNPs的长度

除了Python中的matches计算之外,我已经把所有的东西都计算好了。我迄今为止的做法是:

for i in range(0, len(uniqueSNPs)):
    totalNucleotides = previousState.count(uniqueSNPs[i])
    for j in range(0, len(uniqueSNPs)):
        matches = sum((previousState == uniqueSNPs[i]) & 
            (currentState == uniqueSNPs[j]))
        mat[i,j] = matches / totalNucleotides

但是,我在计算matches的行上得到一个错误,它表示 TypeError: 'bool' object is not iterable。 我想知道是否有一种方法可以用Python以简洁高效的方式编写这行代码?我对Python编程比较陌生,所以我不知道有什么好的技巧

谢谢


Tags: in基因组列表forlenrangesum核苷酸