对于此列表:
list = [1,5,7,11,23,8,45,18]
如何为列表中的每个值计算最接近的值? 在这种情况下,输出如下:
'value' 1 : 5
'value' 5 : 7
'value' 7 : 8
'value' 11 : 8
'value' 23 : 18
'value' 8 : 7
'value' 45 : 23
'value' 18 : 23
答案 0 :(得分:1)
这是一种实现方法:
lst = [1, 5, 7, 11, 23, 8, 45, 18]
srt = sorted(lst)
nearest_dct = {srt[0]: srt[1], srt[-1]: srt[-2]}
for low, n, high in zip(srt[:-2], srt[1:-1], srt[2:]):
nearest_dct[n] = low if n - low < high - n else high
# nearest_dct = {1: 5, 45: 23, 5: 7, 7: 8, 8: 7, 11: 8, 18: 23, 23: 18}
res = [nearest_dct[n] for n in lst]
# [5, 7, 8, 8, 18, 7, 23, 23]
这样,仅在列表上进行一次迭代(好的,它需要首先对列表进行排序...)。一种改进是使用islice
而不是常规切片。这里是一个更直接的版本:
from itertools import islice
srt = [-float('inf'), *sorted(lst), float('inf')]
nearest_dct = {n: low if n - low < high - n else high for low, n, high in
zip(srt, islice(srt, 1, None, None), islice(srt, 2, None, None))}
res = [nearest_dct[n] for n in lst]
# [5, 7, 8, 8, 18, 7, 23, 23]