如何使函数返回所有可能的值

2024-06-11 12:14:45 发布

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

所以我正在使用这个方法,它可以很好地查找数字,但它只返回最后一个值。有没有办法让它在每次运行后返回所有值。 这是我的密码:

def searchPFAM():

    fileAddress = '/Volumes/interpro/data/Q14591.txt'
    start = None
    end = None
    with open(fileAddress,'rb') as f:
        root = etree.parse(f)
        for lcn in root.xpath("/protein/match[@dbname='PFAM']/lcn"):#find dbname =PFAM
            start = int(lcn.get("start"))#if it is PFAM then look for start value
            end = int(lcn.get("end"))#if it is PFAM then also look for end value
            print start, end
        return start, end

Tags: noneforgetifisitpfamroot
3条回答

只需修改函数即可创建并返回开始元组和结束元组的列表:

def searchPFAM():
    fileAddress = '/Volumes/interpro/data/Q14591.txt'
    start = None
    end = None
    result = []
    with open(fileAddress,'rb') as f:
        root = etree.parse(f)
        for lcn in root.xpath("/protein/match[@dbname='PFAM']/lcn"):#find dbname =PFAM
            start = int(lcn.get("start"))#if it is PFAM then look for start value
            end = int(lcn.get("end"))#if it is PFAM then also look for end value
            print start, end
        result.append((start, end))
    return result

可读性稍差,但更简洁有效的写作方法是使用已知的“列表理解”,如下所示:

def searchPFAM():
    fileAddress = '/Volumes/interpro/data/Q14591.txt'
    start = None
    end = None
    with open(fileAddress,'rb') as f:
        root = etree.parse(f)
        result = [(int(lcn.get("start")), int(lcn.get("end"))) 
                     for lcn in root.xpath("/protein/match[@dbname='PFAM']/lcn")]
    return result

之后,您可以像这样处理返回的列表:

for start,end in result:
   ... # do something with pair of int values

或者

for i in xrange(len(result)):
   start,end = result[i][0],result[i][1]
   ... # do something with pair of int values

您可以创建一个包含start和end的元组列表,并在函数末尾返回该列表。你知道吗

你是说类似的事吗?你知道吗

def do_something(fname):
    with open(fname,'rb') as f:
        root = etree.parse(f)
        for lcn in root.xpath("/protein/match[@dbname='PFAM']/lcn"):#find dbname =PFAM
            # Make slightly more robust
            try:
                start = int(lcn.get("start"))#if it is PFAM then look for start value
                end = int(lcn.get("end"))#if it is PFAM then also look for end value
                yield start, end
            except (TypeError , ValueError) as e:
                pass # start/end aren't usable as numbers decide what to do here...

for start, end in do_something():
    do_something_else(start, end)

相关问题 更多 >