如何使用其他lis拆分列表

2024-03-27 17:37:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张单子。两者都是经过排序的数字列表。说:

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_valuestransformed_remainder。你知道吗

How can you compute transformed_values and transformed_remainder efficiently from the variables A and B? Perhaps it can be done directly without computing listoflists 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有太多的开销,使用对分会更好。)


Tags: and代码距离列表value数字matharray
2条回答

您可以使用以下代码:

a = [1.1, 5.2, 12.3, 12.6]
b = [2.3, 2.7, 5.2, 11.1, 12.1, 15.6, 16.6]

for i in a:
    nearest = None
    nearestNum = None
    for x in b:
        if nearest == None:
            nearest = abs(i - x)
            nearestNum = x
        if abs(i - x) < nearest:
            nearestNum = x
            nearest = abs(i - x)
    if nearestNum:
        print(i, "->", nearestNum)
    else:
        print(i, "-> Not found")

#or

for i in a:
    nearest = []
    nearestNum = None
    for x in b:
        nearest.append(abs(i - x))
    nearest.sort()
    if i + nearest[0] in b:
        nearestNum = i + nearest[0]
    elif i - nearest[0] in b:
        nearestNum = i - nearest[0]
    if nearestNum:
        print(i, "->", nearestNum)
    else:
        print(i, "-> Not found")

我想你不需要帮助。这就是如何进行转换的方法。你知道吗

transformed_values = (
    listoflists[0] 
    + [[a - prior[-1], b - prior[-1]] 
       for (a, b), prior in zip(listoflists[1:], listoflists[:-1])]
)
transformed_remainder = [r - listoflists[-1][-1] for r in B[(len(A) + 1):]]

相关问题 更多 >