这并不是一个特定于任何代码的问题,也不是我遇到的问题,但为了了解我想知道的知识。
比如说,我有以下代码:
# list1 and list2 are determinied off the screen
if len(list1) > 0:
cycler = list1
elif len(list2) > 1:
cycler = list2
else:
cycler = []
for id in cycler:
t = Thing._by_id(id)
# a lot of stuff done with t
在第三种情况下,cycler = []
,for 循环是否花费了任何资源/时间,或者 for 循环是否立即中断?我根本不担心这个,事实上,我在一个函数中有这个,它在 else 子句中返回,我只是好奇。
最佳答案
不是我的代码,但如果我们看这里,我们会看到时间用于创建这个“空列表”。
% python -mtimeit "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop
% python -mtimeit "l=list()"
1000000 loops, best of 3: 0.297 usec per loop
就实际迭代列表而言,是的,这也会消耗资源。解释器至少必须知道列表是空的,因此它必须进入内存位置以查看它是否为空。
关于python - 对空列表进行 for 循环实际上会花费时间/资源吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33510806/