[英]read in data from a text file and have each column as a list in python
Here is the data in a text file i am importing: 这是我要导入的文本文件中的数据:
-2, 2.1, 0.484147876841
0, 2.4, 0.0550985751073
2, 2.5, -0.48502362586
4, 3.5, -0.161922119386
6, 4.2, 0.442947234586
I would like each column of data into a separate list, to look like: 我希望将每一列数据都放在一个单独的列表中,如下所示:
x = [-2, 0,2 ,4 ,6]
y = [2.1, 2.4, 2.5, 3.5, 4.2]
e = [0.484147876841, 0.0550985751073, -0.48502362586, -0.161922119386, 0.442947234586]
I tried the following code: 我尝试了以下代码:
inputdata=open("C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'r')
for datapoint in inputdata:
datapoint=datapoint.strip('\n')
splitdata=datapoint.split(',')
x.append(splitdata[0])
y.append(splitdata[1])
e.append(splitdata[2])
What error are you receiving? 您收到什么错误? Try this, it worked for me: 试试这个,对我有用:
inputdata=open("C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'r')
x = []
y= []
e = []
for datapoint in inputdata:
datapoint=datapoint.strip('\n')
splitdata=datapoint.split(',')
x.append(int(splitdata[0]))
y.append(float(splitdata[1]))
e.append(float(splitdata[2]))
print x
print y
print e
Output : 输出 :
[-2, 0, 2, 4, 6]
[2.1, 2.4, 2.5, 3.5, 4.2]
[0.484147876841, 0.0550985751073, -0.48502362586, -0.161922119386, 0.442947234586]
Here's one way to do it: 这是一种实现方法:
input_file = 'data.txt'
with open(input_file) as f:
a = [map(float, line.strip('\n').split(',')) for line in f]
x, y, z = [list(l) for l in zip(*a)]
print(x, y, z)
Prints: 印刷品:
[-2.0, 0.0, 2.0, 4.0, 6.0] [2.1, 2.4, 2.5, 3.5, 4.2] [0.484147876841, 0.0550985751073, -0.48502362586, -0.161922119386, 0.442947234586]
If you don't mind that x
, y
, and z
will be tuples, you can use just zip(*a)
instead of wrapping each element with a list in the last list comprehension. 如果您不介意x
, y
和z
将是元组,则可以仅使用zip(*a)
而不是在最后一个列表理解中用列表包装每个元素。
First, you may need to convert to the correct datatype: 首先,您可能需要转换为正确的数据类型:
x.append(int(splitdata[0]))
y.append(float(splitdata[1]))
e.append(float(splitdata[2]))
...
Second, this is a csv file, and you might better process it with the right library: 其次,这是一个csv文件,您最好使用正确的库对其进行处理:
import csv
with open(r"C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'rb') as csvfile:
reader = csv.reader(csvfile):
for row in file:
x.append(int(row[0]))
...
file1=open("D:\price.txt","r")
x=[]
y=[]
z=[]
for i in file1:
x.append(i.strip().split())
print(x)
for i in x:
y.append(int(i[0]))
z.append(int(i[1]))
print(y,z)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.