gpt4 book ai didi

python - 我需要将包含数据的文本文件读入 python 并将数据分配给变量

转载 作者:太空宇宙 更新时间:2023-11-03 15:14:51 26 4
gpt4 key购买 nike

文件中的数据如下所示;需要表示 X 和 Y 值的两列。中的第一个值将是 X 值,第二个值将是 Y 值。

   42.10      8.55
40.25 7.60
38.50 8.95
39.55 6.45
40.90 7.75

我需要将它读入 python 并为每一行中的每组值分配变量:例如,(42.10,8.55) 其中 42.10 是 x 值,8.55 是 y 值。有几条值(value)观需要这种组织。我可以打开文件并读入它,但是我无法获得我想要的变量赋值。

到目前为止我有

with open ("file.txt", "r") as myfile:
data=myfile.read().split()

好的,现在这是我现在的位置:

with open('file.txt') as f:
data = [line.split() for line in f.readlines()]
out = [(float(x), float(y)) for x, y in data]
for i in out:
print i

我想在 for 循环中创建数据的散点图,您会推荐哪个模块?

最佳答案

data = []
for line in open(myfile).readlines():
temp_x,temp_y = line.split()
x = float(temp_x)
y = float(temp_y)
data.append((x,y))

您可以变得更漂亮,但这就是您开始所需要的。

您只获得 x 和 y 的最新值的原因是 x 和 y 在循环的每次迭代中都会更改它们的值。查看所有值

for each_pair in data:
(x, y) = each_pair
print 'X = ',x, 'Y = ', y

关于python - 我需要将包含数据的文本文件读入 python 并将数据分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211634/

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