我做了一些测试:
test_lists.py
a = range(1, 1000)
b = range(2, 1002)
tmp = []
for i in a:
if(i not in b):
tmp.append(i)
test_set_list_comprehensions.py
a = range(1, 1000)
b = range(2, 1002)
b = set(b)
[aa for aa in a if aa not in b]
测试集.py
a = range(1, 1000)
b = range(2, 1002)
list(set(a).difference(set(b)))
这就是 timeit 所说的:
~$ python -m timeit 'import test_lists'
1000000 loops, best of 3: 0.671 usec per loop
~$ python -m timeit 'import test_set_list_comprehension'
1000000 loops, best of 3: 0.766 usec per loop
~$ python -m timeit 'import test_set'
1000000 loops, best of 3: 0.656 usec per loop
所以最好的似乎是:
测试集.py
a = range(1, 1000)
b = range(2, 1002)
list(set(a).difference(set(b)))