【问题标题】:Python function doesnt work inside a loopPython函数在循环内不起作用
【发布时间】:2019-06-09 01:40:01
【问题描述】:

我正在尝试创建一个代码来比较基因文件和基因面板。 基因面板文件为 csv 格式,具有染色体、基因、起始位置和结束位置。 患者档案有染色体、突变和位置。 所以我做了一个循环,将基因面板信息传递给一个函数,在该函数中进行比较以返回一个相似项目的列表。 当我使用手动数据调用该函数时,该函数效果很好。但不要在循环内进行比较。

import vcf
import os, sys

records = open('exampleGenePanel.csv')
read = vcf.Reader(open('examplePatientFile.vcf','r'))

#functions to find mutations in patients sequence
def findMutations(gn,chromo,start,end):
    start = int(start)
    end = int(end)
    for each in read:
        CHROM = each.CHROM
        if CHROM != chromo:
            continue
        POS = each.POS
        if POS < start:
            continue
        if POS > end:
            continue
        REF = each.REF
        ALT = each.ALT
        print (gn,CHROM,POS,REF,ALT)
        list.append([gn,CHROM,POS,REF,ALT])
    return list

gene = records.readlines()

list=[]
y = len (gene)
x=1
while x < 3:
    field = gene[x].split(',')
    gname = field[0]
    chromo = field[1]
    gstart = field[2]
    gend = field[3]
    findMutations(gname,chromo,gstart,gend)
    x = x+1
if not list:
    print ('Mutation not found')
else:
    print (len(list),' Mutations found')
    print (list)

我想获取列表中匹配突变的详细信息。 当我手动将数据传递给函数时,这可以按预期工作。 eg.findMutations('TESTGene','chr8','146171437','146229161') 但是通过循环时不比较

【问题讨论】:

  • 您比较了该语句,但如果该语句为 True,则您没有执行任何操作。

标签: python function loops vcf-variant-call-format


【解决方案1】:

问题是findMutations 每次调用时都会尝试从read 读取,但是在第一次调用之后,read 已经被读取并且什么都没有了。我建议在调用函数之前阅读read 的内容一次,然后将结果保存在列表中。那么findMutations可以在每次调用时读取列表。

使用list 以外的名称作为结果列表也是一个好主意,因为该名称与 Python 内置函数冲突。最好让findMutations 返回其结果列表,而不是将其附加到全局。

【讨论】:

  • 感谢 Tom Karzes 的建议。根据您的建议,我能够更正我的代码,现在它可以完美运行(实际上超出了我的预期)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
相关资源
最近更新 更多