Skip to main content
 首页 » 编程设计

python之"Non-equal"或 "greater than"更快

2025年05月04日15langtianya

我想知道以下哪项对于元组(也适用于列表或整数)完成得更快:

a_tuple = ('a', 'b',) 
  1. if (len(a_tuple) != 0): 通过

  2. if (len(a_tuple) > 0): 通过

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

请您参考如下方法:

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

if a_tuple: 
    pass 

或者,演示胜于 Eloquent :

>>> 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