python从文件中读取数据_如何在python中从文本文件中读取和存储k,m和数据点

"本文介绍了如何使用Python读取文件"data.txt",将其内容转换为浮点数列表,并按行组织成适合进一步计算的数据结构。通过逐行处理,提取x, y, z, t坐标,便于后续数据分析或算法应用。"
摘要由CSDN通过智能技术生成

您不需要m维空间 - 您只需要列表。

创建你的demodata:data = """5 4

1.6 0.3 15.0 14.1

1.3 9.1 0.9 12.4

5.6 9.9 14.4 18.6

25.0 1.3 12.9 2.1

17.2 3.4 9.2 14.7

2.3 2.2 1.2 9.5"""

fn = "file.txt"

with open(fn, "w") as f:

f.write(data)

将其读回到浮点列表列表的合适数据结构中:fn = "file.txt"

all_data = []

with open(fn,"r") as f:

k,m = map(float,f.readline().strip().split())

for line in f:

if line.strip(): # weed out empties

line = list(map(float,line.split()))

all_data.append(line)

print("k:",k,"m:",m)

print(all_data)

给出一个输出:k: 5.0 m: 4.0

[[1.6, 0.3, 15.0, 14.1], # each line is one row of your data

[1.3, 9.1, 0.9, 12.4], # its position the same as in your file

[5.6, 9.9, 14.4, 18.6], # and you can use those in whatever calculations

[25.0, 1.3, 12.9, 2.1], # you need to do

[17.2, 3.4, 9.2, 14.7],

[2.3, 2.2, 1.2, 9.5]]

你有列表中的所有数字,可以从那里开始。

如果你需要他们为x,y,z,t你可以从他们收集all_data使用ZIP(),并利用分解:x,y,z,t = map(list,zip(*all_data))

print(x)

print(y)

print(z)

print(t)

输出:[1.6, 1.3, 5.6, 25.0, 17.2, 2.3] # x

[0.3, 9.1, 9.9, 1.3, 3.4, 2.2] # y

[15.0, 0.9, 14.4, 12.9, 9.2, 1.2] # z

[14.1, 12.4, 18.6, 2.1, 14.7, 9.5] # t

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值