Python 列表搜索优化

Python 列表搜索优化,python,optimization,Python,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) 试试这个: data = [x for x in first if x[0] in second] 假设第一个有m个元素,第二个有n个元素 集合是散列的,因此搜索它们接近O(1),从而给出

有没有更快的方法来做到这一点:

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]
假设第一个有m个元素,第二个有n个元素


集合是散列的,因此搜索它们接近O(1),从而给出O(m)的总体效率。以列表形式搜索第二个是O(n),给出了O(m*n)的总体效率。

也许您只需要这个,而不需要检查中的

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]

data=[x代表x,如果1,则第一个元素中的所有元素都将是selected@Falmarri-编辑以使事情更清楚。谢谢。但Jason Baker的答案正是我想要的。(我在问题中使用了一个非常简单的示例,但如果第二个列表有其他数据类型怎么办?)
data = [x for x in first if 1 <= x[0] <= 5412 ]