txt文件中的两个值之间的差异,python

时间:2015-05-17 10:53:07

标签: python

我在txt文件的每一行都有一些值。现在我想计算

之间的差异
  

line [1] - line [0],line [3] - line [2]

等等。

import sys

l = []
i = 0
f=open('Isotop1.txt')
# i = Zeilennummer, line = text der Zeile
for line in enumerate(f):
    l.append(line)
    for i in l:
        c = l[i] - l[i-1]
        print c


f.close()

稍后我想将解决方案存储在新的文本文件中。 但现在我收到了list indices must be integers, not tuple错误。 有人可以帮忙吗?

这是文本文件中的一个小样本。我想计算33和0,94和61之间的差异,依此类推。也许我对这个问题使用了一种完全错误的方法......

0
33
61
94
122
153
178
200
227
246
274
297
310
324

1 个答案:

答案 0 :(得分:2)

with open("in.txt") as f:
    # get first line/number
    nxt = int(next(f))
    for n in f:
        print("absolute difference between {} and {} = {}"
              .format(n.rstrip(), nxt, abs(int(nxt) - int(n))))
        # set nxt equal to the next number
        nxt = int(next(f,0))

输出:

absolute difference between 33 and 0 = 33
absolute difference between 94 and 61 = 33
absolute difference between 153 and 122 = 31
absolute difference between 200 and 178 = 22
absolute difference between 246 and 227 = 19
absolute difference between 297 and 274 = 23
absolute difference between 324 and 310 = 14

如果您想使用每个号码:

def diff(fle):
    with open(fle) as f:
        nxt = int(next(f))
        for n in f:
            yield abs(int(nxt) - int(n))
            nxt = int(next(f,0))

print(list(diff("in.txt")))
[33, 33, 31, 22, 19, 23, 14]

或迭代并一次获得一个数字:

for n in diff("words.txt"):
    print(n)

输出:

33
33
31
22
19
23
14

使用0作为next的默认值将避免StopIterationError。

如果你正在进行大量的数值计算,那么numpy可能会更好:

import numpy as np

arr = np.loadtxt("words.txt", dtype=np.int)

diff = np.abs(np.diff(arr.reshape(-1,2)).flatten())

print(diff)