我想知道对于一个元组(也是一个列表或一个int),以下哪个更快完成:
a_tuple = ('a', 'b',)
if (len(a_tuple) != 0): pass
if (len(a_tuple) > 0): pass
我做了一些timeit实验,结果非常相似(每次运行10000次迭代时都会有所不同)。我只是想知道是否有时间好处。
答案 0 :(得分:7)
使用not a_tuple
(True
,如果为空)或tuple
(True
,如果不为空),而不是测试长度:
if a_tuple:
pass
或者,作为一个演示胜于雄辩:
>>> if not ():
... print('empty!')
...
empty!
>>> if (1, 0):
... print('not empty!')
...
not empty!
除了这是微优化的事实之外,对空元组的虚假测试也更快。如果对速度有疑问,请使用timeit
模块:
>>> import timeit
>>> a_tuple = (1,0)
>>> def ft_bool():
... if a_tuple:
... pass
...
>>> def ft_len_gt():
... if len(a_tuple) > 0:
... pass
...
>>> def ft_len_ne():
... if len(a_tuple) != 0:
... pass
...
>>> timeit.timeit('ft()', 'from __main__ import ft_bool as ft')
0.17232918739318848
>>> timeit.timeit('ft()', 'from __main__ import ft_len_gt as ft')
0.2506139278411865
>>> timeit.timeit('ft()', 'from __main__ import ft_len_ne as ft')
0.23904109001159668