简体   繁体   English

TypeError:“ Route”对象不可下标Python

[英]TypeError: 'Route' object is not subscriptable Python

This is a script I have that reads a JSON file and adds routes to a graph 这是我拥有的脚本,可读取JSON文件并向图添加路线

 for route in data['routes']:
        route = Route(route['ports'][0], route['ports'][1], route['distance'])
        self.add_route(route)
        route_2 = Route (route['ports'][1], route['ports'][0], route['distance'])
        self.add_route(route_2)

It gives me this error: 它给了我这个错误:

Traceback (most recent call last):
  File "C:\workspace\Assignment2.1\src\Main.py", line 75, in <module>
    graph.build_from_file()
  File "C:\workspace\Assignment2.1\src\Graph.py", line 195, in build_from_file
    route_2 = Route (route['ports'][1], route['ports'][0], route['distance'])
TypeError: 'Route' object is not subscriptable

Notice it gives an error at the second call of the Route constructor not first. 注意,它在Route构造函数的第二次调用而不是第一次调用时给出了错误。 Can anyone help me out with this? 谁能帮我这个忙吗?

You named two different things route . 您为两条不同的route命名。

After you created your first Route , the route variable is pointing to it instead of your datum. 创建第一个Routeroute变量将指向它而不是您的基准。

Fixed code: 固定代码:

for route in data['routes']:
    route_1 = Route(route['ports'][0], route['ports'][1], route['distance'])
    self.add_route(route_1)
    route_2 = Route(route['ports'][1], route['ports'][0], route['distance'])
    self.add_route(route_2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM