如果另一个列表中的元素的差异小于某个值,如何对列表的元素求和

How to sum the elements of a list if the difference of elements in another list is less than a certain value

鉴于两个列表具有相同的大小。我想先计算一个列表中连续元素之间的差异,然后在差异满足条件的情况下对第二个列表中的相应元素求和。

例如:

List_1 = [0.1, 0.2, 0.3, 0.5, 0.6, 0.9]
List_2 = [1, 1, 1, 1, 1, 1]

如果List_1中的连续元素之间的差异小于或等于0.1,我想对List_2中的相应元素求和。如果差异大于 0.1,则什么也不做。在这种情况下,List_1 的差异是 [0.1, 0.1, 0.2, 0.1, 0.3] 那么我预期的总和列表是 [ 3, 2, 1].

下面的代码本质上是使用 slicing and Python's built-in function zipfor 循环提供合适的迭代器。我试图向 print 添加一些解释性调用以显示发生了什么:

# Your list input
X = [0.1, 0.2, 0.3, 0.5, 0.6, 0.9]
Y = [1, 2, 4, 8, 16, 32]

# Calculate sums
Z = [Y[0]]
for x_1, x_2, y in zip(X, X[1:], Y[1:]):
    print(f"Z currently looks like this: {Z}")
    print(f"Is {x_1} to {x_2} leq 0.1? {x_2 - x_1 <= 0.1}", end=" ")
    if x_2 - x_1 <= 0.1:
        print(f"=> Add {y} to last sum in Z")
        Z[-1] += y
    else:
        print(f"=> Use {y} to start a new sum in Z")
        Z += [y]

print("Final result:", Z)

将打印:

Z currently looks like this: [1]
Is 0.1 to 0.2 leq 0.1? True => Add 2 to last sum in Z
Z currently looks like this: [3]
Is 0.2 to 0.3 leq 0.1? True => Add 4 to last sum in Z
Z currently looks like this: [7]
Is 0.3 to 0.5 leq 0.1? False => Use 8 to start a new sum in Z
Z currently looks like this: [7, 8]
Is 0.5 to 0.6 leq 0.1? True => Add 16 to last sum in Z
Z currently looks like this: [7, 24]
Is 0.6 to 0.9 leq 0.1? False => Use 32 to start a new sum in Z
Final result: [7, 24, 32]

当然,您可以只删除对 print 的所有调用,代码仍然有效。