3 回答
TA贡献1856条经验 获得超17个赞
用于str.split在一行上拆分数据,str.split返回字符串列表。
例子:
>>> strs = "1.2 1.6 0.4"
>>> strs.split()
['1.2', '1.6', '0.4']
#use slicing as you need only first two items
>>> [float(x) for x in strs.split()[:2]]
[1.2, 1.6]
如果只需要每行的前两列:
mylist=[]
with open('x.dat') as f:
for line in f:
#apply int to the items of `str.split` to convert them into integers
x, y = [float(z) for z in line.split()[:2]]
mylist.append(Point(x, y))
如果您只想读取前两行:
mylist=[]
with open('x.dat') as f:
rows = 2
for _ in xrange(rows):
line = next(f)
x, y, k = [float(z) for z in line.split()]
mylist.append(Point(x, y, k))
对类定义进行一些更改:
class point():
def __init__(self,x = None,y =None,k =None,f =None):
self.x = 0 if x is None else x #assign default value only if the value was not passed
self.y = 0 if y is None else y
self.k = 0 if k is None else k
self.f = -1 if f is None else f
添加回答
举报