评估循环条件中的表达式

wjk*_*2a1 1 python

对于某些n,让我们按以下方式定义结果:

result = [x for x in [i for i in range(0, n)]]
Run Code Online (Sandbox Code Playgroud)

python每次都会评估内部列表吗?或者它只在第一次评估它?因为这是O(n)O(n^2)的运行时间之间的差异。
例如:

result = [x for x in func()]
Run Code Online (Sandbox Code Playgroud)

python每次迭代都会调用函数func吗?

这可能是重复的,我只是在任何地方都找不到它。

Dee*_*ace 5

你为什么不自己尝试一下呢?

def foo():
    print('foo called')
    return range(5)


result = [x for x in [i for i in foo()]]
print(result)
>>  foo called
    [0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

foo显然被调用了一次。