【问题标题】:Storing multiple values from single function in python在python中存储单个函数的多个值
【发布时间】:2013-10-10 02:57:04
【问题描述】:

这个函数打印多个值,它们是字符串 z 的索引,但是我想存储这些值,使用 return 将终止函数,只留下几个值的第一个值。

def find(a):
    index=a
    while index<len(z)-1:
        if z[index]=="T":
            for index in range (index+20,index+30):
                if z[index]=="A" and z[index+1]=="G" and z[index+2]=="T":
                    a=index
                    print a
        index=index+1

【问题讨论】:

标签: python recursion return


【解决方案1】:

最直接的方法是返回tuplelist

def find(a):
    index=a
    ret = []
    while index<len(z)-1:
        if z[index]=="T":
            for index in range (index+20,index+30):
                if z[index]=="A" and z[index+1]=="G" and z[index+2]=="T":
                    a=index
                    ret.append(a)
        index=index+1
    return ret

您也可以使用yield。我正在删除它的代码(您可以阅读链接,它非常好),因为我认为在您的情况下返回 listyield 更有意义。如果您不打算总是使用所有返回的值,或者如果返回值太多而无法保存在内存中,yield 会更有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多