【发布时间】:2020-05-06 04:39:57
【问题描述】:
我需要在第二个脚本的函数中使用第一个脚本中的一些数据,但不确定在我的情况下如何正确执行此操作。我希望有一个简单的答案,但不幸的是,我被困在了这个问题上。
第一个脚本的结尾是
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()
但这并不能保持我需要的正确对象类型。一些有关使用所需语法的指导将不胜感激。
如果进一步的上下文有用,我正在使用的 scriptA 和 scriptB 与示例代码非常相似
https://developers.google.com/optimization/routing/vrp
和 https://developers.google.com/optimization/routing/tsp 分别在 Google OR-Tools 文档中。
【问题讨论】:
-
这是因为您使用的是 print 而不是在第一个函数中返回。此外,不需要: if name == 'main': main()
-
好的,我认为这有帮助
标签: python traveling-salesman or-tools object-type