在循环语句中调用函数,时间与空间之间的权衡?

时间:2019-01-30 01:15:17

标签: python-3.x loops sorting

在leetcode上,我遇到了许多代码片段,其中的循环看起来像这样:

for x in sorted(vals):
    ...........

每次我们到达for语句时,sorted()都会被调用吗?因此,分别存储排序后的列表然后迭代该列表是否更好?

1 个答案:

答案 0 :(得分:1)

(假设使用Python 3)

实际上,它只被调用一次。

Python 3.7.2 (default, Jan 10 2019, 23:51:51) 
[GCC 8.2.1 20181127] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def notify_sorted(l):
...     print("Invoked!")
...     return sorted(l)
... 
>>> for x in notify_sorted([1,2,3]):
...     print(x)
... 
Invoked!
1
2
3