2013-01-23 72 views
1

我不知道這下面是一個元組(也可用於列表或一個int)做得更快:「不等於」或「大於」更快?

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

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

我做一些timeit實驗,結果非常相似(每次運行timeit進行100000次迭代時都會有所不同)。我只是想知道是否有時間利益。

+6

這樣的微觀優化很少有益。如果你需要速度,把它外包給C. – Xophmeister

回答

7

的長度使用not a_tupleTrue如果爲空)或tupleTrue如果不爲空),而不是測試:

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

此外,它快兩倍。 – bereal

+0

等待,如果你有一個空元組的實例,它如何「如果a_tuple」爲假? – Ivaylo

+0

@Ivaylo:因爲空元組是'虛假'的。在布爾上下文中,它測試爲False,就像空字符串或0(任何數字類型)。見http://docs.python.org/2/reference/expressions.html#boolean-operations –