"不平等"或"大于"更快?

Iva*_*ylo 1 python python-2.7 python-3.x

我想知道对于元组(也用于列表或int),以下哪个更快完成:

a_tuple = ('a', 'b',)
Run Code Online (Sandbox Code Playgroud)
  1. if (len(a_tuple) != 0): pass

  2. if (len(a_tuple) > 0): pass

我做了一些timeit实验,结果非常相似(每次运行10000次迭代时都会有所不同).我只是想知道是否有时间的好处.

Mar*_*ers 7

使用not a_tuple(True如果为空)或tuple(True如果不为空)而不是测试长度:

if a_tuple:
    pass
Run Code Online (Sandbox Code Playgroud)

或者,作为一个演示胜于雄辩:

>>> if not ():
...     print('empty!')
...
empty!
>>> if (1, 0):
...     print('not empty!')
...
not empty!
Run Code Online (Sandbox Code Playgroud)

除了这是微优化的事实之外,对空元组的虚假测试也更快.如果对速度有疑问,请使用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
Run Code Online (Sandbox Code Playgroud)