这是我的代码:
class typeE:
def __init__(self):
self.u = 0
self.v = 0
self.w = 0
def readData():
global n
global m
global e
e = [typeE]
c = -2
f = open(fi, 'r')
for line in f:
print e[0]
c += 1
ln = [int(i) for i in line.split()]
if c == -1:
n = ln[0]
m = ln[1]
else:
e[c].u = ln[0]
e[c].v = ln[1]
e[c].w = ln[2]
f.close()
你知道如何在Python中创建这样的记录吗?
type
typeE = record
u, v, w: longint;
end;
答案 0 :(得分:0)
Python不是Pascal。你不会创建一系列记录"但是"对象列表" (可以是实例自定义类,但在您的情况下也可以是纯dict
s)。
此外,无论语言是什么,全局变量都是一个坏主意,使用真正的函数(根据输入返回结果的函数,而不是变异或重新绑定全局变量)总是更好。
你的代码的pythonic版本(预留错误处理)看起来像这样:
class TypeE(object):
def __init__(self, u=0, v=0, w=0):
self.u = u
self.v = v
self.w = w
def __repr__(self):
return "<TypeE({u}, {v}, {w})>".format(**self.__dict__)
def to_int(line):
return [int(i) for i in line.strip().split()]
def read_data(src):
records = []
with open(src, 'r') as f:
headers = to_int(f.next())[:2]
for line in f:
records.append(TypeE(*ln[:3]))
return headers, records
def main():
(m,n), e = read_data("/path/to/your/file")
# now do something with m, n and e
print m, n, e
if __name__ == "__main__":
main()