如何将文本文件数据存储为变量,然后使用这些变量计算值?

时间:2019-11-18 21:23:38

标签: python

我是python的新手,我有一个文本文件,如下所示:

0       10
0.01    10.0000001
0.02    10.00000113
0.03    10.00000468
0.04    10.0000128

分别是时间和速度的前几个值。

我想将文本文件读入Python,并使用这些值创建时间和速度变量,以查找加速度。

到目前为止,我有:

t = []
v = []

with open('data.txt', 'r') as f:
    for line in f:
        first, second = line.split()
        t.append(first)
        v.append(second)


print(t)
print(v)

现在我不确定下一步要去哪里。

理想情况下,我想计算相应时间的加速度,然后将其写入具有[时间,加速度]的新文本文件中,如下所示:

0       acceleration_value1
0.01    acceleration_value2
0.02    acceleration_value3
0.03    acceleration_value4
0.04    acceleration_value5

3 个答案:

答案 0 :(得分:1)

您的大多数代码已经存在,但是缺少从文件读取的字符串到float的转换。除此之外,一个简单的循环就可以完成这项工作。

t = []
v = []

with open('data.txt', 'r') as f:
    for line in f:
        first, second = line.split()
        t.append(float(first))    # note the 'float' conversion here
        v.append(float(second))

# Now, we will use an array to store the acceleration values
# The first element in this array will be zero, so:
a = [0]

# To calculate the acceleration, we will do delta(v)/delta(t),
# To calculate any delta, we will iterate each array, and pick
# the "current" and "previous" element. For this reason, our index
# will start at 1 skipping the first (otherwise we'll go to -1)

# these steps could be combined, but I feel it helps beginners to see
# the process

for i in range(1, len(v)):    # since v,t have same length, just pick either
    delta_v = v[i] - v[i-1]
    delta_t = t[i] - t[i-1]
    acc = delta_v / delta_t
    a.append(acc)

# Now we can print
# 'zip' combines the two arrays as columns of a matrix,
# so now "x" picks a value from "t", and "y" from "a" 
# as we iterate
for x, y in zip(t, a):
    print("%s  %s" % (x,y))

# or save to file:
with open("acceleration.txt", 'w') as f:
    for x, y in zip(t, a):
        f.write("%s  %s\n" % (x,y))

答案 1 :(得分:0)

这应该给出每个时间戳的加速度列表

t = []
v = []

with open('data.txt', 'r') as f:
    for line in f:
        first, second = line.split()
        t.append(first)
        v.append(second)

acc = []
for i in range(len(t)):
  if i == 0:
    acc.append(0)
  else:
    acc.append((float(v[i]) - float(v[i-1])) / (float(t[i]) - float(t[i-1])))

print(acc)

答案 2 :(得分:0)

我看不到将它们存储到变量中的必要性,为什么不尝试访问压缩列表中的每个值对?

zipped= list(zip(t,v))