使用NumPy数组(对于大型数组,速度更快)可以检查列表的长度,然后检查重叠部分,类似以下内容(显然将较长的切片为较短的长度):
import numpy as np
n = min(len(test1), len(test2))
x = np.where(test1[:n] != test2[:n])[0]
if len(x) > 0:
ans = x[0]
elif len(test1) != len(test2):
ans = n
else:
ans = None
编辑 - 尽管这个回答被投票否决,但我会把我的答案留在这里,以防其他人需要做类似的事情。
如果起始数组很大并且使用numpy,则这是最快的方法。此外,我不得不修改安迪的代码才能使其正常工作。按顺序:1. 我的建议,2. Paidric的(现已删除,但最优雅),3. 安迪的被接受的答案,4. zip-非numpy,5. 没有zip的vanilla python,如@leekaiinthesky所述。
0.1ms,9.6ms,0.6ms,2.8ms,2.3ms
如果将转换为ndarray包含在timeit中,则非numpy nop-zip方法最快
7.1ms,17.1ms,7.7ms,2.8ms,2.3ms
如果两个列表之间的差异在大约1,000而不是10,000的索引处,则更是如此
7.1ms,17.1ms,7.7ms,0.3ms,0.2ms
import timeit
setup = """
import numpy as np
from itertools import zip_longest
list1 = [1 for i in range(10000)] + [4, 5, 7]
list2 = [1 for i in range(10000)] + [4, 4]
test1 = np.array(list1)
test2 = np.array(list2)
def find_first_diff(l1, l2):
for index, (x, y) in enumerate(zip_longest(l1, l2, fillvalue=object())):
if x != y:
return index
def findFirstDifference(list1, list2):
minLength = min(len(list1), len(list2))
for index in range(minLength):
if list1[index] != list2[index]:
return index
return minLength
"""
fn = ["""
n = min(len(test1), len(test2))
x = np.where(test1[:n] != test2[:n])[0]
if len(x) > 0:
ans = x[0]
elif len(test1) != len(test2):
ans = n
else:
ans = None""",
"""
x = np.where(np.in1d(list1, list2) == False)[0]
if len(x) > 0:
ans = x[0]
else:
ans = None""",
"""
x = test1
y = np.resize(test2, x.shape)
x = np.where(np.where(x == y, x, 0) == 0)[0]
if len(x) > 0:
ans = x[0]
else:
ans = None""",
"""
ans = find_first_diff(list1, list2)""",
"""
ans = findFirstDifference(list1, list2)"""]
for f in fn:
print(timeit.timeit(f, setup, number = 1000))