簡體   English   中英

如果另一個列表中元素的差異小於某個值,如何對列表的元素求和

[英]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_2如果在連續元素之間的差List_1小於或等於0.1。 如果差值大於 0.1,則什么都不做。 在這種情況下, List_1的差異是[0.1, 0.1, 0.2, 0.1, 0.3]那么我預期的總和列表是[ 3, 2, 1]

以下代碼本質上使用 切片和 Python 的內置函數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調用,代碼仍然可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM