Python 如何使函数返回所有可能的值
所以我使用编写这个方法,它在查找数字方面效果很好,但它只返回最后一个值。是否有办法使它在每次运行后返回所有值。 这是我的密码:Python 如何使函数返回所有可能的值,python,return,lxml,Python,Return,Lxml,所以我使用编写这个方法,它在查找数字方面效果很好,但它只返回最后一个值。是否有办法使它在每次运行后返回所有值。 这是我的密码: def searchPFAM(): fileAddress = '/Volumes/interpro/data/Q14591.txt' start = None end = None with open(fileAddress,'rb') as f: root = etree.parse(f) for l
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
你是说类似的事情吗
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)
您可以创建开始元组和结束元组列表,只需在函数末尾返回该列表。只需修改函数即可创建并返回开始元组和结束元组列表:
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
可读性稍差,但更紧凑、更高效的写作方法是使用knowm作为“列表理解”,如下所示:
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
之后,您可以按如下方式处理返回的列表:
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
或
如果我有一个列表,那么我是否能够将起始值和结束值作为int传递,或者在传递之前我是否需要另一个方法来读取它them@ChadD:您可以从列表中提取每个元组,然后在
for
循环中提取该元组的每个整数。类似于“开始,以结果结束:…”的。您还可以直接访问返回的列表中的任意一个,如result[n][0]
和result[n][1]
,以获取第n个的开始值和结束值。我是否可以将这些值传递到另一个方法上。。或者我必须结合另一种方法,以便在我的两个method@ChadD是的,您可以将这些值与其他函数一起使用。@AshwiniChaudhary我是否只将start和end作为参数传递,或者我需要做些什么,因为我之前使用的是start,end=searchPFAM()这行吗?我认为jon clements使用的for循环完全可以<代码>开始,结束于做某事():做某事(开始,结束)
让我们