tldr; 将B 转换为set 并使用列表推导式。 @Krishna Chaurasia 对set(B) 的理解是提出的最快解决方案。
正如其他人所建议的那样,您绝对应该使用set(B) 进行搜索。这提高了大型 B 的性能。
现在提高大型A 的性能,因此提高C 的性能。预分配C。请注意,预分配仅在替换 append() 的情况下才有用,它不会加快理解速度。
from timeit import timeit
setup = '''
A = list(range(1000000))
B = set(range(500000, 1500000))
'''
stmt_for_no_preallocation = '''
C = []
for x in A:
if x in B:
C.append(1)
else:
C.append(0)
'''
stmt_for_preallocation = '''
C = [0] * len(A)
for i, x in enumerate(A):
if x in B:
C[i] = 1
'''
stmt_comp = 'C = [1 if x in B else 0 for x in A]'
stmt_comp_map = '''
B_map = {elt: True for elt in B}
C = [1 if B_map.get(x, False) else 0 for x in A]
'''
stmt_comp_map_alias_get = '''
B_map = {elt: True for elt in B}
get = B_map.get
C = [1 if get(x, False) else 0 for x in A]
'''
n = 10
print('for without preallocating C')
print(timeit(stmt_for_no_preallocation, setup=setup, number=n))
print('for with preallocating C')
print(timeit(stmt_for_preallocation, setup=setup, number=n))
print('list comprehension')
print(timeit(stmt_comp, setup=setup, number=n))
print('list comprehension with map')
print(timeit(stmt_comp_map, setup=setup, number=n))
print('list comprehension with map and alias B_map.get to local scope')
print(timeit(stmt_comp_map_alias_get, setup=setup, number=n))
输出:
对于没有预分配 C
0.900570491
用于预分配 C
0.723135233
列表理解
0.51548745
用地图列出理解
1.5568766299999997
使用 map 和别名 B_map.get 到本地范围的列表理解
1.3334449179999996