我需要几个小时的python,我正在尝试编写一个脚本,它从一个文件(名为'peaks.dat')读取一组x,y坐标,并将它们填入一个列表(类类型); 我正在定义以下内容:
class point():
def _init_(self,x=None,y=None,k=None,f=None):
self.x=0 # x coordinate
self.y=0 # y coordinate
self.k=0 # I need these for later stuff
self.f=-1 # I need these for later stuff
Run Code Online (Sandbox Code Playgroud)
但后来我找不到任何方法从文件中的一行(即,两列中只有一列中的元素)中"选取"单个元素,而不是整行.有这样的事吗?
无论如何,我尝试将我的列分成两个不同的文件x.dat和y.dat,但后来我不知道如何从文件中单独填充我的'point'类型列表的x和y字段.我试过了
f=open('x.dat','r')
mylist=[]
for line in f:
mylist.append(point(line, , , )) # wrong syntax D:
f.close()
for data in mylist:
print i.x
Run Code Online (Sandbox Code Playgroud)
计划在y.dat文件中稍后使用,但在许多级别上似乎都是错误的.
ps我来自一些C++,如果你想举例.
编辑:peaks.dat只是三列(我只需要前两个)数字,类似于
1.2 1.6 0.4
1.5 2.1 0.3
1.1 1.0 0.5
Run Code Online (Sandbox Code Playgroud)
等等
x.dat(或y.dat)是一行数字.
根据文件的格式,您要么使用该csv模块,要么使用该str.split()功能.
对于行上以空格分隔的值,请使用str.split():
points = []
with open(inputfilename) as infile:
for line in infile:
row = [int(i) for i in line.split()]
# row is now a list of integers.
points.append(point(*row))
Run Code Online (Sandbox Code Playgroud)
对于其他格式,通常csv模块是最佳选择:
import csv
points = []
with open(inputfilename, 'rb') as infile:
reader = csv.reader(infile, delimiter='\t') # tab delimited file
for row in reader:
row = [int(i) for i in row]
# row is now a list of integers.
points.append(point(*row))
Run Code Online (Sandbox Code Playgroud)
要只读两行,请使用next()两次; csv版本:
for _ in range(2):
row = [int(i) for i in next(reader)]
# row is now a list of integers.
points.append(point(*row))
Run Code Online (Sandbox Code Playgroud)
next()从迭代器中获取下一个项目; 两个infile对象和reader对象是产生文件中的行或行的CSV迭代器.
或者,使用itertools.islice()实用程序:
for row in islice(reader, 2): # only yield the first two rows.
Run Code Online (Sandbox Code Playgroud)