这是一个不使用 NumPy 的有点密集的单行代码:
>>> from itertools import combinations
>>> a = [10, 7, 3, 6]
>>> closest_pair = min((abs(x-y), (i, j)) for (i,x), (j, y) in combinations(enumerate(a), 2))[1]
>>> closest_pair
(1, 3)
这是它的工作原理...
combinations
用于创建所有对:
>>> list(combinations(a, 2))
[(10, 7), (10, 3), (10, 6), (7, 3), (7, 6), (3, 6)]
我们需要元素的索引,因此修改为:
>>> list(combinations(enumerate(a), 2))
[((0, 10), (1, 7)),
((0, 10), (2, 3)),
((0, 10), (3, 6)),
((1, 7), (2, 3)),
((1, 7), (3, 6)),
((2, 3), (3, 6))]
列表推导作用于这个结果并形成一个新的绝对差异列表和相应的索引对:
>>> [(abs(x - y), (i, j)) for (i,x), (j, y) in combinations(enumerate(a), 2)]
[(3, (0, 1)), (7, (0, 2)), (4, (0, 3)), (4, (1, 2)), (1, (1, 3)), (3, (2, 3))]
取最小值给出元组,其第一个值为最小绝对距离,第二个值为索引的元组:
>>> min((abs(x - y), (i, j)) for (i,x), (j, y) in combinations(enumerate(a), 2))
(1, (1, 3))
最后,只从该结果中提取索引:
>>> min((abs(x - y), (i, j)) for (i,x), (j, y) in combinations(enumerate(a), 2))[1]
(1, 3)