TypeError:“dict_keys”对象不可订阅,为 VRP 构建解决方案[已关闭]

问题描述 投票:0回答:1

我在 Python 代码中遇到 TypeError:

'dict_keys' object is not subscriptable
。这是我的代码的一部分: 我有
class solution
具有此功能:

`def _assign_request(self, request_id, route_id, position):

  position = int(position)
  # Remove the request from the request bank
  self.request_bank.remove(request_id)
  # Add the pickupnode at position 1
  self.routes[route_id].insert_node(1, request_id)
  # Add the delivery node at position "position"
  self.routes[route_id].insert_node(position,
                                  request_id + self.problem.n)
  # Set the delta_f to None for the inserted request for ALL routes
  # self._delta_f[request_id, :] = numpy.NaN for id in range(len(self.routes)):
    self._delta_f[request_id][id] = float('Nan')
# Set the _best_insert_position to -1 for the inserted request
# for ALL routes
# self._best_insert_position[request_id, :] = -1
for id in range(len(self.routes)):
    self._best_insert_position[request_id][id] = -1
# Update the insert matrix for the route to which the request was
# assigned
self._update_best_insert_route(route_id)`

我有以下功能:

` def _get_start_solution(self, problem):
        solution = Solution(problem)
        available_requests = problem.requests.copy()  # Make a copy to prevent modifying the original list
        random.shuffle(available_requests)  # Shuffle for randomness
    while solution._is_next_insert_possible() and len(available_requests) > 0:
        # Choose a random vehicle
        vehicle_id = random.choice(solution.available_vehicles)  # Removed []
        vehicle = solution.routes[vehicle_id]  # Get the vehicle object using the vehicle_id
        request_id = random.choice(solution.request_bank)  # Get a random request_id

        # Choose a random position in the route to insert the request
        if len(vehicle.route) > 0:
            position = random.randint(0, len(vehicle.route))
        else:
            position = 0  # If the route is empty, insert at the start

        # Assign request to the route at the chosen position
        solution._assign_request(request_id, vehicle, position)

        # Remove the request from available requests
        available_requests.remove(request_id)

    # Keep only the used vehicles/routes and rebuild matrices
    solution.routes = [route for route in solution.routes[:solution._number_of_used_vehicles()]]
    solution._rebuild_insert_matrices()

    return solution`

这是回溯的一部分:

Traceback (most recent call last):
  File "C:\Users\hajar\Desktop\lns_v_test_epsilon\lns\test_alpha_gamma.py", line 128, in <module>
    main()
  File "C:\Users\hajar\Desktop\lns_v_test_epsilon\lns\test_alpha_gamma.py", line 124, in main
TypeError: 'dict_keys' object is not subscriptable`

get_start_solution 必须为有能力的车辆路径问题创建一个随机初始解决方案,执行代码时我得到“dict_keys”对象不可下标`

python-3.x list vehicle-routing
1个回答
0
投票

我不确定确切的问题,因为您提供的代码不足以识别它,但是您分享的错误

Traceback (most recent call last):
  File "C:\Users\hajar\Desktop\lns_v_test_epsilon\lns\test_alpha_gamma.py", line 128, in <module>
    main()
  File "C:\Users\hajar\Desktop\lns_v_test_epsilon\lns\test_alpha_gamma.py", line 124, in main
TypeError: 'dict_keys' object is not subscriptable

清楚地表明您正在尝试通过索引来访问

dict_keys
项目,这是不可能的。如果要使用索引访问键,则需要首先将
dict_keys
对象转换为可以索引的对象,例如
list
tupple
:

foo = {'bar':0}

try:
   key = foo.keys()[0]
except:
   print('It doesnt work...')
   key = list(foo.keys())[0]
   print('... but now it does! ->', key)

请注意,

foo.keys()
返回一个
<class dict_keys>
类型的对象,可以对其进行迭代(但不建立索引)以获取索引和键本身:

foo = {'bar0':0, 'bar1':10}

for ii, key in enumerate(foo.keys()):
   print('Key index: ', ii)
   print('Key name: ', key)

© www.soinside.com 2019 - 2024. All rights reserved.