<p>感谢@MattMessersmith,我已经实现了我的最终解决方案,它满足了2个需求:</p>
<ol>
<li>筛选两个列表中彼此太近的项</li>
<li><p>在两个彼此接近的列表中匹配项</p>
<pre><code>list1 = [7, 22, 34, 49, 56, 62, 76, 82, 89, 149, 161, 182]
list2 = [7, 14, 49, 57, 66, 76, 135, 142, 161]
>>> result = match_approximate(list1, list2, 3)
>>> print result[0]
>>> print result[1]
[7, 49, 56, 76, 161]
[7, 49, 57, 76, 161]
>>> result = match_approximate(list1, list2, 1, True)
>>> print result[0]
>>> print result[1]
[22, 34, 62, 82, 89, 149, 182]
[14, 66, 135, 142]
</code></pre></li>
</ol>
<p>代码如下:</p>
<pre><code> def match_approximate(a, b, approx, invert=False):
a_ind, b_ind = 0, 0
resulta, resultb = [], []
while a_ind < len(a) and b_ind < len(b):
aItem, bItem = a[a_ind], b[b_ind]
if abs(aItem - bItem) <= approx:
if not invert:
resulta.append(aItem)
resultb.append(bItem)
a_ind += 1
b_ind += 1
continue
if aItem < bItem:
if invert:
resulta.append(aItem)
a_ind += 1
else:
if invert:
resultb.append(bItem)
b_ind += 1
if invert:
while a_ind != len(a):
resulta.append(a[a_ind])
a_ind += 1
while b_ind != len(b):
resulta.append(b[b_ind])
b_ind += 1
return [resulta, resultb]
</code></pre>