我有两张单子。两者都是经过排序的数字列表。说:
A = [1.1, 5.2, 12.3, 12.6]
B = [2.3, 2.7, 5.2, 11.1, 12.1, 15.6, 16.6]
对于A中的每个数字,我在B中找到最接近的值
1.1 -> 2.3
5.2 -> 5.2
12.3 -> 12.1
12.6 -> 12.1
我现在想使用这个映射将B拆分为一个列表列表。某个值映射到的每一点都作为一个区间的终点。所以我明白了
listoflists = [[2.3], [2.7, 5.2], [11.1, 12.1]]
剩下的是:
remainder = [15.6, 16.6]
现在我需要将listoflists中的值转换为距离listoflists中上一个列表末尾的值的距离。我们假设在0处有一个隐式值。所以:
transformed_values = [[2.3], [0.4, 2.9], [5.9, 6.9]]
余数类似于:
transformed_remainder = [3.5, 4.5]
我一直在努力编写合理和正确的代码来输出transformed_values
和transformed_remainder
。你知道吗
How can you compute
transformed_values
andtransformed_remainder
efficiently from the variablesA
andB
? Perhaps it can be done directly without computinglistoflists
at all?
我有代码可以找到最接近的值:
def find_nearest(array, value):
idx = np.searchsorted(array, value, transformed_remainderside="left")
if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
return array[idx-1]
else:
return array[idx]
(我需要经常这样做,所以可能使用numpy有太多的开销,使用对分会更好。)
您可以使用以下代码:
我想你不需要帮助。这就是如何进行转换的方法。你知道吗
相关问题 更多 >
编程相关推荐