[英]How to store textfile data as variables and then calculate values using those variables?
我是 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)
現在我不確定下一步該去哪里。
理想情況下,我想計算相應時間的加速度,然后將其寫入具有 [time, acceleration] 的新文本文件,如下所示:
0 acceleration_value1
0.01 acceleration_value2
0.02 acceleration_value3
0.03 acceleration_value4
0.04 acceleration_value5
您的大部分代碼已經存在,但是它缺少從文件讀取的字符串轉換為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))
這應該給出每個時間戳的加速度列表
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)
我是 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)
現在我不確定接下來要去哪里 go 。
理想情況下,我想計算相應時間的加速度,然后將其寫入具有 [時間,加速度] 的新文本文件,如下所示:
0 acceleration_value1
0.01 acceleration_value2
0.02 acceleration_value3
0.03 acceleration_value4
0.04 acceleration_value5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.