2013-07-17 42 views

回答

1

由於您將首先重複檢查元素是否在b,convert b to a set之間,因此每次檢查是O(1)而不是O(n)。然後你可以使用list comprehension

[el for el in a if el[0] in bset] 

a = [(1, 'CA'), (2, 'NY')] 
b = [2,3,4,5,6] 
bset = set(b) 

a = [el for el in a if el[0] in bset] 
print(a) 

產量

[(2, 'NY')] 

注:如果a是非常短的,轉換成一組實際速度是:

In [4]: %timeit bset = set(b); [el for el in a if el[0] in bset] 
1000000 loops, best of 3: 580 ns per loop 

In [5]: %timeit [el for el in a if el[0] in b] 
1000000 loops, best of 3: 335 ns per loop 

但是,如果a長,然後轉換b一組是值得的:

In [47]: a = a*1000 

In [48]: %timeit bset = set(b); [el for el in a if el[0] in bset] 
10000 loops, best of 3: 157 us per loop 

In [49]: %timeit [el for el in a if el[0] in b] 
10 loops, best of 3: 37.2 ms per loop 
+0

謝謝!順便說一句,這種操作叫什麼?我想查找更多關於它的信息。謝謝! –

+0

這兩個主要思想是[sets](http://docs.python.org/2/library/sets.html)和[list comprehensions](http://docs.python.org/tutorial/datastructures.html#列表內涵)。 – unutbu

1

這裏是一個一行。 bset=set(b)只執行一次

>>> a = [(1, 'CA'), (2, 'NY')] 
>>> b = [2, 3, 4, 5, 6] 
>>> a[:] = filter(lambda x, bset=set(b): x[0] in bset, a) 
>>> a 
[(2, 'NY')]