從串列中獲取第一個值的最快和最好的方法是什么?有多種技術,但什么是最好的(記憶體和速度),為什么?
下面的例子。我也會感謝其他技術:
listis = [1, 2, 3, 4]
### 1:
###----------
value = next(iter(listis))
print(value)
### 2:
###----------
value = listis[0]
print(value)
### 3:
###----------
value, *args = listis
print(value)
uj5u.com熱心網友回復:
value = listis[0]在這里將是無與倫比的,因為它只是創建一個新名稱 ( value) 參考listis[0].
更重要的是,您的實際意思很明顯。這會讓下一個查看你的代碼的人(可能就是你)的生活變得更好。
嘗試:
import timeit
print(timeit.timeit("value = next(iter(listis))", setup="listis = [1, 2, 3, 4]", number=1_000_000))
print(timeit.timeit("value = listis[0]", setup="listis = [1, 2, 3, 4]", number=1_000_000))
print(timeit.timeit("value, *args = listis", setup="listis = [1, 2, 3, 4]", number=1_000_000))
這會告訴你這value = listis[0]是最快的。
0.0976
0.0264
0.1190
uj5u.com熱心網友回復:
通過元素編號呼叫串列元素始終是最快的方法。您沒有進行任何計算,也沒有使用任何函式來獲得它。
print(listis[0])
uj5u.com熱心網友回復:
listis[0]
這是任何情況下的最佳選擇。
list創建Python是為了使其元素可通過[i]語法訪問。
例如這段代碼...
listis[-1]
...將回傳最后一個元素。
這段代碼...
listis[::-1]
...將反轉串列
這段代碼...
listis[2:]
...將回傳沒有前兩個元素的串列。
uj5u.com熱心網友回復:
我們可以比較這三種方式:
這里的腳本:
import numpy as np
from matplotlib import pyplot as plt
from time import time
def nrml(lst):
value = lst[0]
def it(lst):
value = next(iter(lst))
def arg(lst):
value, *args = lst
def test():
res = []
for i in range(100, 100000, 100):
the_lst = [0] * i
nrml_s = time()
nrml(the_lst)
nrml_e = time()
it_s = time()
it(the_lst)
it_e = time()
arg_s = time()
arg(the_lst)
arg_e = time()
res.append(
[
i,
nrml_e - nrml_s,
it_e - it_s,
arg_e - arg_s
]
)
res = np.array(res)
plt.plot(res[:, 0], res[:, 1], label="Indexing")
plt.plot(res[:, 0], res[:, 2], label="Iter")
plt.plot(res[:, 0], res[:, 3], label="Unpack")
plt.legend()
plt.show()
if __name__ == '__main__':
test()
請注意,我們沒有檢查記憶體使用情況。只是時間。
結果如下:

請注意Iter和Indexing關閉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394125.html
上一篇:Python,seleniumwebdriverchrome,從很多網頁元素里面獲取頁面原始碼
下一篇:二叉樹每一片葉子的路徑
