Python 2 阅读行问题

Python 2 readline issue

我正在尝试构建一些离散优化算法(构建 djisktra、flowd warshall 和 bellman ford),我在 python3 中构建了它,但实际上我在 python2 中需要它,问题来了...

这是我的代码:

import os.path

def dict_fromFile():
    fn = os.path.join(os.path.dirname(__file__), 'metroEdgeDist.txt')
    f = open(fn, 'r')
    i=0
    dict_voisins = {}
    nb_sommets = f.readline()
    list_temp = {}
    for line in f:
        nb_voisins = line
        for nb in range(0,int(nb_voisins)):
            tempSommet = f.readline()
            tempPoids = f.readline()
            list_temp.update({int(tempSommet.replace("\n","")):float(tempPoids.replace("\n",""))})
        dict_voisins[i]= list_temp
        list_temp = {}
        i+=1
    f.close()
    return dict_voisins

def mat_fromFile():
    fn = os.path.join(os.path.dirname(__file__), 'metroEdgeDist.txt')
    f = open(fn, 'r')
    i=0
    nb_sommets = int(f.readline())
    mat_voisins = [[ float('inf') for i in range(nb_sommets) ] for j in range(nb_sommets) ]
    for line in f:
        nb_voisins = line
        for nb in range(0,int(nb_voisins)):
            tempSommet = f.readline()
            tempPoids = f.readline()
            mat_voisins[i][int(tempSommet.replace("\n",""))] = float(tempPoids.replace("\n",""))
        mat_voisins[i][i]=0 
        i+=1
    f.close()
    return mat_voisins

所以问题是"Mixing iterations"...但实际上我不知道这样做有什么不同...

问题是我需要 for 循环中的那些 "readline()",因为我正在尝试读取 2 行并将它们存储在变量中...

该代码是我用来根据输入实际创建邻接矩阵和字典的代码 输入数据的形式为:

304 #total number of vertex
1 #vertex number 0 has 1 neighbor
1 #the 1st neighbor o 0 is 1
1.067 # the value of the edge bteween 0 & 1 is 1.067
2 #vertex number 1 has 2 neighbors
0 #first neighbor is vertex 0
1.067 #value of edge is 1.067
2 #second neighbor is vertex 2
0.848 #value of edge is 0.848
2 #vertex 2 has 2 neighbors ...
1
0.848

因此,如果您想到更好的方式来读取文件或如何更正我的混合迭代问题!!

谢谢各位大佬!!

两种可能的解决方案: 1) 一个 while 循环,里面有所有 3 个 readlines

2) 你保留 for 循环并使用一个(或两个)变量来记住你处于哪个阶段