簡體   English   中英

python三元組的累積總和?

[英]python cumulative sum of triples?

我的數據是:

li = [('a', 10, 'b'), ('b', 12, 'c'), ('c', 5, 'd'), ('b', 2, 'e')]

a是開始。

執行應該是這樣的:

a = 0
b = a + 10
c = b + 12
d = c + 5
e = b + 2

S到底:

a=0 b=10 c=22 d=27 e=12

我想過用樹和遞歸來計算,但我很茫然,不知道如何編寫這些代碼。

使用defaultdict將使這個任務變得非常簡單:

from collections import defaultdict

res = defaultdict(int)
for source, operand, target in li:
    res[target] = res[source] + operand

for key,val in res.items():
    print(key, "=", val)

會給:

a = 0
b = 10
c = 22
d = 27
e = 12

您需要直接訪問命名空間中的變量嗎?

from sys import modules

main = modules["__main__"]

li=[('a',10,'b'),('b',12,'c'),('c',5,'d'),('b',2,'e')]

a = 0
for var_1, num, var_2 in li:
    setattr(main, var_2, getattr(main, var_1) + int(num))

print(f"a={a}", f"b={b}", f"c={c}", f"d={d}", f"e={e}", sep='\n')                                                                   

輸出:

a=0
b=10
c=22
d=27
e=12

暫無
暫無

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

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