我知道使用 bisect 模块可能是一个很好的解决方案:
>>> def sort_relative(L1, L2):
# Switch if needed
if L1[0] > L2[0]:
L1, L2 = L2, L1
i = 0
while i + 1 < max(len(L1), len(L2)):
try:
# We know that L1[i] < L2[i]
# Get indexes where L2[i] and L2[i + 1] should be inserted
i11 = bisect.bisect_left(L1, L2[i])
i12 = bisect.bisect_left(L1, L2[i + 1])
# This condition allows to know if one element of L1
# was found between L2[i] and L2[i + 1]:
# - if so, we have L1[i] < L2[i] < L1[i + 1] < L2[i + 1]
# - else we have L1[i] < L2[i] < L1[i + 1] but
# we don't know between L1[i + 1] and L2[i + 1]
if L1[i11] < L2[i + 1]:
L1 = L1[:i + 1] + [L1[i11]] + L1[i12:]
index1, index2 = i + 1, i + 2
else:
L1 = L1[:i + 1] + L1[i12:]
index1, index2 = i, i + 1
# Do the same kind of symetric search,
# with indexes computed above
i21 = bisect.bisect_left(L2, L1[index1])
i22 = bisect.bisect_left(L2, L1[index2])
if L2[i21] < L1[index2]:
L2 = L2[:index1] + [L2[i21]] + L2[i22:]
else:
L2 = L2[:index1] + L2[i22:]
# Little trick not to test indexes everywhere:
# lists are browsed at the same time
except IndexError:
pass
# Next index !
i += 1
# Show result
print 'L1:', L1, '- L2:', L2
>>> sort_relative([1, 10, 50], [15, 30])
L1: [1, 50] - L2: [15]
>>> sort_relative([17, 18, 50], [15, 30])
L1: [15, 30] - L2: [17, 50]
>>> sort_relative([1, 10, 12, 25, 27, 50], [15, 30, 70])
L1: [1, 25, 50] - L2: [15, 30, 70]
>>> sort_relative([1, 10, 12, 25, 27, 50], [15, 30, 34, 70])
L1: [1, 25, 50] - L2: [15, 30, 70]
>>>
我没有考虑数字同时在A
和中的情况B
。