【问题标题】:Python - How do I keep returning values from a function with a while statement?Python - 如何使用 while 语句继续从函数返回值?
【发布时间】:2016-01-30 07:57:29
【问题描述】:

因此,下面概述的代码将参数发送到我创建的名为 bsearch 的函数,我希望函数 main() 发送带有关键参数的参数从 11 (11,10,9,8,7...) 按比例缩小 1 直到达到 0 我希望每次输出的值计数 --- 目前它只返回第一个计数。如何让它在每个 while 循环后返回?

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

【问题讨论】:

  • 尝试使用生成器并利用yield关键字
  • 使用return 语句会退出当前的def 代码块,因此在while 循环的第一次迭代后,代码停止运行
  • 使用yield就是答案。

标签: python function while-loop return


【解决方案1】:

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

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

或使用 cmets 中建议的列表推导:

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

【讨论】:

  • 您还可以使用列表推导来使其更短。返回 [ bsearch(x) for x in range(1,11) ]
猜你喜欢
  • 2020-07-09
  • 1970-01-01
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多