在M/PowerQuery中,除了递归,还有其他方法可以更快、更有效地从列表中查找最接近的匹配值。
一种方法是使用内置的函数来实现。在PowerQuery中,可以使用List.Sort函数对列表进行排序,然后使用List.FirstN函数获取排序后的列表中的前几个元素。接下来,可以使用List.Min函数找到最接近的匹配值。
另一种方法是使用二分查找算法。二分查找是一种高效的查找算法,适用于有序列表。首先,需要对列表进行排序。然后,可以使用二分查找算法来查找最接近的匹配值。
以下是使用这两种方法的示例代码:
方法一:使用内置函数
let
sourceList = {1, 5, 3, 9, 7, 2, 4, 6, 8},
targetValue = 5,
sortedList = List.Sort(sourceList),
closestValues = List.FirstN(sortedList, 3),
closestMatch = List.Min(closestValues, (x) => Number.Abs(x - targetValue))
in
closestMatch
方法二:使用二分查找算法
let
sourceList = {1, 5, 3, 9, 7, 2, 4, 6, 8},
targetValue = 5,
sortedList = List.Sort(sourceList),
binarySearch = (list as list, target as number) =>
let
low = 0,
high = List.Count(list) - 1,
closestMatch = null
in
while low <= high do
let
mid = Number.RoundDown((low + high) / 2),
midValue = list{mid}
in
if midValue = target then midValue
else if midValue < target then
let
nextLow = mid + 1,
nextHigh = high
in
if closestMatch = null or Number.Abs(midValue - target) < Number.Abs(closestMatch - target) then
closestMatch = midValue,
low = nextLow,
high = nextHigh
else
high = mid - 1
else
let
nextLow = low,
nextHigh = mid - 1
in
if closestMatch = null or Number.Abs(midValue - target) < Number.Abs(closestMatch - target) then
closestMatch = midValue,
low = nextLow,
high = nextHigh
else
low = mid + 1,
high = nextHigh
in
closestMatch,
closestMatch = binarySearch(sortedList, targetValue)
in
closestMatch
这些方法都可以在PowerQuery中使用,以更快、更有效地从列表中查找最接近的匹配值。
领取专属 10元无门槛券
手把手带您无忧上云