Python - 如何使用while语句继续从函数返回值?

时间:2015-10-29 23:55:57

标签: python function while-loop return

因此,下面列出的代码向我创建的一个名为 bsearch 的函数发送参数,我希望函数 main()使用key参数发送参数从11(11,10,9,8,7 ...)缩小1,直到达到0,我想要每次输出的值计数---目前它只返回第一个计数。如何在每次循环后返回它?

def main():
    ilist = [x+1 for x in range(10)]
    key = 11
    start = 0
    end = 10
    while key > 0:
        count = b(ilist,key,start,end)
        key = key -1
        return count

1 个答案:

答案 0 :(得分:2)

我想你可能想看一些教程,但我想你想要这样的东西:

def main():
    count_list = []
    for x in range(1,11):
        count_list.append(bsearch(x))  # append your results to a list
    return count_list  # return out of the scope of the loop

或使用评论中建议的列表理解:

def main():
    return [bsearch(x) for x in range(1,11)]
相关问题