我需要读入一个带有数据的文本文件到Python中,并将数据分配给变量 [英] I need to read in a text file with data into python and assign the data the variables

查看:111
本文介绍了我需要读入一个带有数据的文本文件到Python中,并将数据分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件中的数据如下所示;两列需要表示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值。有几种价值观需要这种组织。我可以打开文件并读取它,但是我无法获得我想要的变量赋值。



到目前为止我有

  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]
为我进出:
print i

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

解决方案

data 和 out 在这里用列表理解:

  with open('text.txt')as f:
data = [line
out = [(float(k),float(v))for k,v in data]
<.flit() / pre>

输出:

  for i in out:
print i

(42.1,8.55)$ (40.25,7.6)
(38.5,8.95)
(39.55,6.45)
(40.9,7.75)

如果您愿意,可以将这些分配给变量,或者可以使用 out [0] 等引用它们。 / b>

如何命名它们取决于您拥有的数量,不过这里有一个例子:

 >>> first_tuple = out [0] 
>>> print first_tuple
(42.1,8.55)


The data in the file looks like this; two columns that need to represent X and Y values. The first value in the will be X values and second value will be Y values.

   42.10      8.55
   40.25      7.60
   38.50      8.95
   39.55      6.45
   40.90      7.75

I need to read it into python and assign variables to each set of values in each line: for example, (42.10,8.55) where 42.10 is the x value and 8.55 is the y value. There are several lines of values that need this kind of organization. I can open the file and read it in however I can't get the variable assignments I want.

so far I have

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

Ok, so now here's where I'm at now:

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

I want to create a scatter plot of the data in the for Loop, which module would you recommend?

解决方案

data and out are constructed here with list comprehensions:

with open('text.txt') as f:
    data = [line.split() for line in f.readlines()]
    out = [(float(k), float(v)) for k, v in data]

output:

for i in out:
    print i

(42.1, 8.55)
(40.25, 7.6)
(38.5, 8.95)
(39.55, 6.45)
(40.9, 7.75)

You can assign these to variables if you want, or you could reference them with out[0] etc.

How you go about naming them all depends on how many you have, but here is an example anyhow:

>>> first_tuple = out[0] 
>>> print first_tuple
(42.1, 8.55)

这篇关于我需要读入一个带有数据的文本文件到Python中,并将数据分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆