效率:在空列表中使用x与判断长度是否大于0
抱歉,这个问题的标题有点难起。
如果我想遍历一个可能是空的列表,哪种方式更有效呢?我预计这个列表大部分时间都是空的。
for x in list:
dostuff()
或者
if len(list)>0:
for x in list:
dostuff()
4 个回答
0
第一种写法更有效率,因为Python的for循环本来就会检查列表的长度,所以再额外加一个检查就是浪费计算机的处理能力。
1
首先,if len(list) > 0:
这段代码可以简化成 if list:
,这样更容易看懂。我原本以为加上这个 if
语句是多余的,但 timeit
这个工具似乎让我改变了看法。看起来(除非我犯了什么低级错误),检查一个列表是否为空会让代码在处理空列表时运行得更快:
$ python -m timeit 'list = []' 'for x in list:' ' print x'
10000000 loops, best of 3: 0.157 usec per loop
$ python -m timeit 'list = []' 'if list:' ' for x in list:' ' print x'
10000000 loops, best of 3: 0.0766 usec per loop
1
你可以直接用 if list:
这个写法。
In [15]: if l:
....: print "hello"
....:
In [16]: l1= [1]
In [17]: if l1:
....: print "hello from l1"
....:
hello from l1
In [21]: %timeit for x in l:pass
10000000 loops, best of 3: 54.4 ns per loop
In [22]: %timeit if l:pass
10000000 loops, best of 3: 22.4 ns per loop
如果一个列表是空的, if list
会被判断为 False
,所以就不需要再去检查 len(list)
的长度了。
2
根据timeit
模块的时间测试结果:
>>> from timeit import timeit
>>> timeit('for x in lst:pass', 'lst=[]')
0.08301091194152832
>>> timeit('if len(lst)>0:\n for x in lst:\n pass', 'lst=[]')
0.09223318099975586
看起来,当列表是空的时候,直接使用for
循环会更快,所以无论列表的状态如何,这都是一个更快的选择。
不过,还有一个明显更快的选择:
>>> timeit('if lst:\n for x in lst:\n pass', 'lst=[]')
0.03235578536987305
使用if lst
比检查列表的长度或者总是使用for
循环要快得多。不过,这三种方法都挺快的,所以如果你想优化你的代码,我建议你先找出真正的瓶颈是什么——可以看看什么时候优化是过早的?。