python - 在第二个脚本函数中传递来自第一个 python 脚本主函数的数据

标签 python traveling-salesman or-tools object-type

我需要在第二个脚本的函数中使用第一个脚本中的一些数据,但不确定在我的情况下如何正确执行此操作。我希望有一个简单的答案,但不幸的是,我陷入了困境。

第一个脚本的结尾是

def main():

  data = create_data()
  addresses = data['addresses']
  API_key = data['API_key']
  distance_matrix = create_distance_matrix(data)
  print(distance_matrix)
if __name__ == '__main__':
  main()

程序打印出类似的内容

[[0, 486348, 155151, 780965, 761151, 254349], [486474, 0, 594180, 422167, 590566, 262043], [155151, 594054, 0, 888671, 868857, 362056], [781506, 421262, 889213, 0, 295098, 495764], [761786, 590592, 869492, 295059, 0, 612583], [254304, 260708, 362011, 495807, 612769, 0]]

我可以将此程序命名为“scriptA”

在第二个脚本中,我想使用“scriptB”

import scriptA

并修改脚本B中手动输入的函数如下

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = [[0, 383429, 118275, 223206, 209301, 405420], [383498, 0, 413976, 422167, 590566, 262043], [117759, 412902, 0, 335203, 315389, 355002], [223635, 421262, 335387, 0, 295098, 495764], [210227, 590592, 315667, 294775, 0, 612583], [405701, 260708, 354835, 495807, 612769, 0]]  # yapf: disable
    data['num_vehicles'] = 1
    data['depot'] = 0
    return data

自动包含第一个脚本中的矩阵。但我不确定这样做的正确代码。我尝试做

data['distance_matrix'] = scriptA.main()

但这并不能维持我需要的正确对象类型。对于所需使用的语法的一些指导将不胜感激。

如果进一步的上下文有用,我使用的 scriptAscriptB 与示例代码非常相似 https://developers.google.com/optimization/routing/vrp
https://developers.google.com/optimization/routing/tsp分别在 Google OR-Tools 文档中。

最佳答案

您必须修改 scriptA 中的 main 函数。您应该返回矩阵而不是打印它。 更新代码:

def main():
  data = create_data()
  addresses = data['addresses']
  API_key = data['API_key']
  distance_matrix = create_distance_matrix(data)
  return distance_matrix

然后调用scriptA.main()将返回数组给您。

关于python - 在第二个脚本函数中传递来自第一个 python 脚本主函数的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59818743/

相关文章:

python - 如何更改默认 Anaconda python 环境

algorithm - 旅行商中的贪心法 VS 动态规划

python - 转换为适当的距离矩阵(对于 TSP)

python - 为什么 AddMultiplicationEquality 仅限于 2 个变量?

python - ORtools 安排学生上课时间冲突

python ,OpenCV : unable to make custom LBP cascade using opencv_traincascade

python - tkinter gui 已关闭但控制台未关闭

algorithm - 这个 MSP 是 TSP 的一个实例吗?

python - 使用重复项约束优化

python - 在 python 中解析大文本的最快方法