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
添加回答
舉報