![](/img/trans.png)
[英]most efficient way to look up the same index number in two different lists to compare values
[英]Most efficient way to look for the last digit of a number?
我最近在Python考試中遇到了一個問題,我們被要求檢查數字是否以8結尾,我遇到了兩種方式,我想知道哪一個最有效,或者是否有更好的方法。
(如果n是所需的數字)那么,方法1:
if n % 10 == 8:
//do stuff here
方法2:
if str(n)[-1] == 8:
//do stuff here
您可以使用Python的內置timeit.timeit
函數輕松地timeit.timeit
:
>>> from timeit import timeit
>>> n = 12345678
>>> timeit("n % 10 == 8", "from __main__ import n")
0.45508130223254284
>>> timeit("str(n)[-1] == '8'", "from __main__ import n")
1.689859186013905
>>>
從上面的結果可以看出,第一種解決方案非常有效,並且比第二種解決方案的性能提高了近四倍。
除了iCodez答案之外,為了獲得更多樂趣和興奮,您可以使用dis
模塊查看說明中的不同之處:
wayne@wango ~ ⚘ python3.4 14:24:49
Python 3.4.0 (default, Mar 25 2014, 15:24:33)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> dis.dis('n % 10 == 8')
1 0 LOAD_NAME 0 (n)
3 LOAD_CONST 0 (10)
6 BINARY_MODULO
7 LOAD_CONST 1 (8)
10 COMPARE_OP 2 (==)
13 RETURN_VALUE
>>> dis.dis('str(n)[-1] == 8')
1 0 LOAD_NAME 0 (str)
3 LOAD_NAME 1 (n)
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 LOAD_CONST 2 (-1)
12 BINARY_SUBSCR
13 LOAD_CONST 1 (8)
16 COMPARE_OP 2 (==)
19 RETURN_VALUE
如果我猜一下,我會說主要的時差與字符串轉換有關。 並快速測試:
>>> from timeit import timeit
>>> n = 12345678
>>> m = "12345678"
>>> timeit("n % 10 == 8", "from __main__ import n")
0.09333206800511107
>>> timeit("m[-1] == '8'", "from __main__ import m")
0.05890634500246961
>>>
顯示這種情況。
此外,在您的代碼中,第二個示例總是等於False
,因為字符串永遠不會==
一個數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.