我需要弄清楚如何读入文件名“berlin52.tsp”的数据
这是我正在使用的格式
NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION : 52
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0
这是我当前的代码
# Open input file
infile = open('berlin52.tsp', 'r')
# Read instance header
Name = infile.readline().strip().split()[1] # NAME
FileType = infile.readline().strip().split()[1] # TYPE
Comment = infile.readline().strip().split()[1] # COMMENT
Dimension = infile.readline().strip().split()[1] # DIMENSION
EdgeWeightType = infile.readline().strip().split()[1] # EDGE_WEIGHT_TYPE
infile.readline()
# Read node list
nodelist = []
N = int(intDimension)
for i in range(0, int(intDimension)):
x,y = infile.readline().strip().split()[1:]
nodelist.append([int(x), int(y)])
# Close input file
infile.close()
代码应读入文件,输出值为“1、2、3...”等的游览列表,同时存储 x 和 y 值以计算距离。它至少可以收集标题。创建节点列表时会出现问题。
这是我得到的错误
ValueError: invalid literal for int() with base 10: '565.0'
我在这里做错了什么?
最佳答案
这是一个 TSPLIB 格式的文件。要在 python 中加载它,请查看 python 包 tsplib95
, 可通过 PyPi 获得或在 Github
文档位于 https://tsplib95.readthedocs.io/
您可以将 TSPLIB 文件转换为 networkx图形并从那里检索必要的信息。
关于python-2.7 - 读入 TSP 文件 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47719924/