gpt4 book ai didi

python - 在循环条件中评估表达式

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:11 24 4
gpt4 key购买 nike

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

result = [x for x in [i for i in range(0, n)]]

python 是否每次都评估内部列表?还是它只在第一次评估它?因为这是 O(n)O(n^2) 运行时间之间的差异。< br/>例如:

result = [x for x in func()]

python 是否每次迭代都调用函数 func

这可能是重复的,我只是找不到它。

最佳答案

你为什么不自己试试呢?

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]

foo 显然被调用了一次。

关于python - 在循环条件中评估表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38811681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com