将2个值存储在一个变量中?

时间:2012-07-10 22:44:58

标签: python store

我想知道,有没有办法可以在我的main方法上存储起始值和结束值。我尝试这样做,但它给了我错误:

def searchM():

    fileAddress = '/database/pro/data/'+ID+'.txt'
    with open(fileAddress,'rb') as f:
        root = etree.parse(f)
        for lcn in root.xpath("/protein/match[@dbname='M']/lcn")
            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
    return "%s, %s" % (start, end,)

values = searchM()

(start, end,) = values

错误消息是UnboundLocalError:在赋值之前引用的局部变量'start'

2 个答案:

答案 0 :(得分:2)

您遇到的错误是由startend变量引起的。首先尝试初始化它们,以便即使没有设置值也存在它们。

此外,您正在尝试创建并返回一个字符串,然后将其解压缩为两个不同的变量。

尝试以下方法:

def searchM():
    fileAddress = '/database/pro/data/%s.txt' % ID
    start = None
    end = None
    with open(fileAddress,'rb') as f:
        root = etree.parse(f)
        for lcn in root.xpath("/protein/match[@dbname='M']/lcn"):
            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
    return start, end

(start, end) = searchM()  

答案 1 :(得分:1)

如果找不到startend,则需要提供值:

for lcn in root.xpath("/protein/match[@dbname='M']/lcn"):
    start = int(lcn.get("start"))
    end = int(lcn.get("end"))
    break
else: # not found
    start = end = None