first = [(1, text, text, 1, 2, 3),
(1, text, text, 1, 0, 3), ... (6054, text, text, 2, 2, 3)]
second = (1, 2, 3, 4, 5 ... 5412)
有沒有做到這一點更快的方法:列表搜索優化
data = [x for x in first if x[0] in second]
first = [(1, text, text, 1, 2, 3),
(1, text, text, 1, 0, 3), ... (6054, text, text, 2, 2, 3)]
second = (1, 2, 3, 4, 5 ... 5412)
有沒有做到這一點更快的方法:列表搜索優化
data = [x for x in first if x[0] in second]
試試這個:
first = [(1, text, text, 1, 2, 3),
(1, text, text, 1, 0, 3), ... (1054, text, text, 2, 2, 3)]
second = (1, 2, 3, 4, 5 ... 5412)
second_set = set(second)
data = [x for x in first if x[0] in second_set]
假設第一有m個元素和第二個有n個元素。
集合被散列,因此搜索它們接近O(1),給出O(m)的總體效率。搜索第二個列表是O(n),給出O(m * n)的總體效率。
哇,謝謝!執行速度真的很明顯...... – Sam 2010-11-26 00:54:01
也許你想的只是這不是in
檢查:
data = [x for x in first if 1 <= x[0] <= 5412 ]
其根本不清楚你想要做什麼。從我所能看到的所有元素開始將被選中 – Falmarri 2010-11-26 00:17:18
@Falmarri - 編輯後使事情更清晰。 – Sam 2010-11-26 00:22:29