2019年1月23日 星期三

[python] 從 list B 中, 找出最接近 list A 的數值串列 (From list of integers, get numbers closest to a given value list)

如何從一組數字 list B 中, 傳回最接近數字 list A 的串列
Key:
min(list_B, key=lambda x:abs(x-mydata) # 從 list_B 傳回 與 mydata 最接近的數字


作法
def test_get_nearest():
   list_A = [10, 20, 30, 40]
   list_B = [11, 22, 33, 44]

   get_nearest(list_A, list_B)   # output: [11, 22, 33, 44]

# 從 list B 中, 找出最接近 list A 的數值串列
def get_nearest(list_A, list_B):
   list_loc_nearest = []
   for loc in list_A:
       list_loc_nearest.append(min(list_B, key=lambda x:abs(x-loc)))
   print('list_loc_nearest = ', list_loc_nearest)


Reference