gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:42:27 24 4
gpt4 key购买 nike

我在 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()

后来我想将解决方案存储在一个新的文本文件中。但现在我得到列表索引必须是整数,而不是元组错误。有人可以帮忙吗?

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

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

最佳答案

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)

关于python - txt文件中两个值之间的差异,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com