Python 中四個高效的技巧!
反轉列表
Python 中通常有兩種反轉列表的方法:切片或 ??reverse()?
? 函數(shù)調用。這兩種方法都可以反轉列表,但需要注意的是內置函數(shù) ??reverse()?
? 會更改原始列表,而切片方法會創(chuàng)建一個新列表。
但是他們的表現(xiàn)呢?哪種方式更有效?讓我們看一下下面的例子:
使用切片:
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist[::-1]'
1000000 loops, best of 5: 15.6 usec per loop
使用 reverse():
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist.reverse()'
1000000 loops, best of 5: 10.7 usec per loop
這兩種方法都可以反轉列表,但需要注意的是內置函數(shù) ??reverse()?
? 會更改原始列表,而切片方法會創(chuàng)建一個新列表。
顯然,內置函數(shù) ??reverse()?
? 比列表切片方法更快!
交換兩個值
用一行代碼交換兩個變量值是一種更具有 Python 風格的方法。
與其他編程語言不同,Python 不需要使用臨時變量來交換兩個數(shù)字或值。舉個簡單的例子:
variable_1 = 100
variable_2 = 500
要交換 ??variable_1?
? 和 ??variable_2?
? 的值,只需要一行代碼。
variable_1, variable_2 = variable_2, variable_1
您也可以對字典使用相同的技巧:
md[key_2], md[key_1] = md[key_1], md[key_2]
該技巧可以避免多次迭代和復雜的數(shù)據(jù)轉換,從而減少執(zhí)行時間。
在函數(shù)內部循環(huán)
我們都喜歡創(chuàng)建自定義函數(shù)來執(zhí)行我們自己的特定任務。然后使用 ??for?
? 循環(huán)遍歷這些函數(shù),多次重復該任務。
但是,在 ??for?
? 循環(huán)中使用函數(shù)需要更長的執(zhí)行時間,因為每次迭代都會調用該函數(shù)。
相反,如果在函數(shù)內部實現(xiàn)了 ??for?
? 循環(huán),則該函數(shù)只會被調用一次。
為了更清楚地解釋,讓我們舉個例子!
首先創(chuàng)建一個簡單的字符串列表:
list_of_strings = ['apple','orange','banana','pineapple','grape']
創(chuàng)建兩個函數(shù),函數(shù)內部和外部都有 ??for?
? 循環(huán),從簡單的開始。
def only_function(x):
new_string = x.capitalize()
out_putstring = x + " " + new_string
print(output_string)
和一個帶有循環(huán)的 ??for?
? 函數(shù):
def for_in_function(listofstrings):
for x in list_of_strings:
new_string = x.capitalize()
output_string = x + " " + new_string
print(output_string)
顯然,這兩個函數(shù)的輸出是一樣的。
然后,讓我們比較一下,哪個更快?
如您所見,在函數(shù)內使用 ??for?
? 循環(huán)會稍微快一些。
減少函數(shù)調用次數(shù)
判斷對象的類型時,使用 ??isinstance()?
? 最好,其次是對象類型標識 ??id()?
?,對象值 ??type()?
? 最后。
# Check if num an int type
type(num) == type(0) # Three function calls
type(num) is type(0) # Two function calls
isinstance(num,(int)) # One function call
不要將重復操作的內容作為參數(shù)放在循環(huán)條件中,避免重復操作。
# Each loop the len(a) will be called
while i < len(a):
statement
# Only execute len(a) once
m = len(a)
while i < m:
statement
要在模塊 X 中使用函數(shù)或對象 Y,請直接使用 ??from X import Y?
? 而不是 ??import X; then X.Y?
?。這減少了使用 Y 時的一次查找(解釋器不必先查找 X 模塊,然后在 X 模塊的字典中查找 Y)。
總而言之,你可以大量使用 Python 的內置函數(shù)。提高 Python 程序的速度,同時保持代碼簡潔易懂。
如果想進一步了解 Python 的內置函數(shù),可以參考下表,或查看以下網(wǎng)站(https://docs.python.org/3/library/functions.html):