【问题标题】:Is a function in a for loop declaration will be called for many times in Python?for循环声明中的函数是否会在Python中被多次调用?
【发布时间】:2018-11-25 21:32:49
【问题描述】:

有一个函数和一个for循环:

def helper():
    return [1,2,3]

for i in helper():
    print(i)

我想知道辅助函数是否只会在 for 循环的初始化时被调用一次。正如我在想,如果我调用函数并将返回数组提前分配给一个变量,它将在 for 循环中使用,如下所示:

def helper():
    return [1,2,3]
temp = helper()
for i in temp:
    print(i)

时间复杂度更低吗?

谢谢!

【问题讨论】:

  • 不,这几乎是一样的,除了你的第一个例子不需要临时变量,所以看起来更干净,更容易阅读等。如果你不确定这样的事情,只需输入打印代码中的语句以查看发生了什么。
  • 只评估一次
  • 您可以通过在helper() 中打印一条消息来自己测试这一点,然后查看该消息是打印一次还是多次打印。
  • 是的,添加一些非常简单的语句print 是您从wonderingknowing 所需的全部内容

标签: python for-loop time-complexity


【解决方案1】:

使用yield操作:

def helper():
    for i in [1,2,3]:
         yield i

for i in helper():
    print(i)

在这种情况下,helper() 方法将在每次迭代期间将 i 值返回给调用 for 循环。

【讨论】:

    猜你喜欢
    • 2021-03-13
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多