我认为,你思维中的一个基本缺陷是,你想读所有的第一行数字,然后读第二行。最好一次通读该文件,而不是在阅读文件时对不同的行进行排序。一种方法是在另一个答案中使用行计数器mod 3,或者您可以继续在for循环中读取行,如下所示:myFileList= """first line
2nd line
3rd line
#Mi Mj
#Ni Nj Nk
#Pi Pj
#----------- The numeric values start here ------
M0 M1
N0 N1 N2
P0 P1
M1 M2
N1 N2 N3
P1 P2
M2 M3
N2 N2 N3
P2 P3"""
myFakeFile = iter(myFileList.split('\n'))
m,n,p = [], [], []
m2, n2, p2 = [], [], []
# Skip the first few lines
for skip_lines in range(7):
next(myFakeFile)
# Read the next line ...
for line in myFakeFile:
# ... and the following two lines
second_line = next(myFakeFile)
third_line = next(myFakeFile)
# Either append line directly,
m.append(line)
n.append(second_line)
p.append(third_line)
# or split the lines before appending
m2.extend(line.split())
n2.extend(second_line.split())
p2.extend(third_line.split())
print('m = {}'.format(m))
print('n = {}'.format(n))
print('p = {}\n'.format(p))
print('m2 = {}'.format(m2))
print('n2 = {}'.format(n2))
print('p2 = {}\n'.format(p2))
我有点不确定您是否希望下次拆分实际的行,因此我添加了m2, n2, p2列表来显示这一点。我必须伪造文件才能得到一个运行的例子。但此代码生成以下输出:
^{pr2}$