python:在obj.func()中为`i执行`每次迭代重新运行`func`?

Ale*_*ird 2 python optimization loops for-loop

假设我有以下代码:

for a in object.a_really_huge_function():
    print a
Run Code Online (Sandbox Code Playgroud)

为了防止a_really_huge_function多次运行,我习惯用其他语言执行此操作:

a_list = object.a_really_huge_function()
for a in a_list:
    print a
Run Code Online (Sandbox Code Playgroud)

这在Python中是必要的吗?部件是否会in在每个循环上运行?

Sam*_*lan 7

python翻译是你的朋友.

>>> def some_func():
...     print 'in some_func'
...     return [1, 2, 3, 10]
... 
>>> for a in some_func():
...     print a
... 
in some_func
1
2
3
10
Run Code Online (Sandbox Code Playgroud)

简而言之,不,它被称为一次.