开发者

List Search Optimization

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)
开发者_如何学C

Is there a faster way to do this:

data = [x for x in first if x[0] in second]


Try this:

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]

Assume first has m elements and second has n elements.

Sets are hashed, so searching them is close to O(1) giving an overall efficiency of O(m). Searching second as a list is O(n) giving an overall efficiency of O(m * n).


Maybe you want just this instead of the in check:

data = [x for x in first if 1 <= x[0] <= 5412 ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜