如何更新变量以跟踪当前值减去Python中的先前值?

时间:2015-09-21 03:34:22

标签: python for-loop text-files

假设我有一个包含以下数据的文本文件:

9.079929479691208
12.97415710230641
29.298703770316134
27.948996122147257
22.226701761850222
24.87655187612297
34.411572810292476

如果文件的名称是text.txt,我尝试过这样做,但它不会工作:

previous_val = 0
current_val = 0
file = open("text.txt","r")
for line in file:
    line = line.strip()
    rows = line.split(" ")
    values = float(rows[0])
    current_val = float(values - previous_val)
    print(current_val)

第一个值应保持与9.079相同...因为之前没有任何内容,但下一个应该是3.whatver因为12.974 ... - 9.079 ... = 3.whatever。它应该在整个过程中继续这样做。当我运行程序时,它只返回文本文件中完全相同的数字。如果有人能帮助我,我会非常感激。谢谢!

4 个答案:

答案 0 :(得分:3)

在每次迭代中更改previous_val。看看这个:

previous_val = 0
file = open("text.txt","r")
for line in file:
    current = float(line.strip())
    print current - previous_val
    previous_val = current  

输出:

9.07992947969
3.89422762262
16.324546668
-1.34970764817
-5.7222943603
2.64985011427
9.53502093417

答案 1 :(得分:1)

在为previous_val赋值为零后,您永远不会更改current_val = float(values - previous_val)的值,因此current_val = float(values)相当于current_val, previous_val = float(values - previous_val), current_val

你想:

current_val

这会将previous_val分配给差异,current_val分配给前一个oAuth

答案 2 :(得分:1)

previous_val = 0
current_val = 0
file = open("text.txt","r")
for line in file:
    line = line.strip()  
    #rows = line.split(" ") # no need to split
    values = float(line)
    current_val = float(values - previous_val)
    print(current_val)
    previous_val = float(line)

答案 3 :(得分:0)

在python3中,你可以使用itertools.accumulate想要你想要的东西:

>>> from itertools import accumulate
>>> with open("text.txt","r") as file:
...     list(accumulate((float(line.strip()) for line in file), lambda a, b: b-a))
[9.079929479691208,
 3.894227622615203,
 25.404476147700933,
 2.544519974446324,
 19.6821817874039,
 5.194370088719072,
 29.217202721573404]

实现累积非常容易,文档中提供了参考实现