问题描述
def find_the_best_solution(shipping_request, list, current_solution, best_shipping_solution):
if shipping_request == {}:
return current_solution
for item in shipping_request:
for i in range(0,len(list), 1):
length_of_combination = i+1
combinations = itertools.combinations(list, length_of_combination)
for x in combinations:
if sum(x) >= shipping_request[item]:
if sum(x) > shipping_request[item]:
current_solution['wastage'] += (sum(x) - shipping_request[item])
current_solution['number_of_containers'] += length_of_combination
current_solution['distribution'][item] = x
temp_request = shipping_request
del temp_request[item]
temp_list = list
for y in x:
temp_list.remove(y)
solution = find_the_best_solution(temp_request, temp_list, current_solution, best_shipping_solution)
if solution['wastage'] < best_shipping_solution['wastage']:
best_shipping_solution = solution
elif solution['wastage'] == best_shipping_solution['wastage']:
if solution['number_of_containers'] < best_shipping_solution['number_of_containers']:
best_shipping_solution = solution
return best_shipping_solution
这将产生以下错误-运行时错误:字典大小在迭代过程中更改"
This gives the following error- "Runtime error: dictionary size changed during iteration"
我做错了什么?我该怎么做?
What am I doing wrong? How can I do it differently?
推荐答案
与itertools.combinations
无关,您试图更改要迭代的数据结构,这是不允许的:
This has nothing to do with itertools.combinations
, you are trying to change the structure of data you are iterating over, which is not allowed:
Runtime error: dictionary size changed during iteration
您正在尝试在字典中添加或删除键.一种解决方法是遍历for key in list(dictionary)
,该for key in list(dictionary)
会创建该词典的键的副本列表,因此您仍然可以修改基础词典,但是您可能还需要重新考虑常规方法.
You are trying to add or delete keys from a dictionary as you iterate it. A workaround is to iterate over for key in list(dictionary)
which makes a copy list of the dictionary's keys, so you can still modify the underlying dictionary, however you may also want to reconsider your general approach.
导致错误的行是:
for item in shipping_request:
for i in range(0,len(list), 1):
...
for x in combinations:
if sum(x) >= shipping_request[item]:
if sum(x) > shipping_request[item]:
...
temp_request = shipping_request
del temp_request[item] # you are trying to delete a key from
# shipping_request as you iterate it
也许您想制作一个浅表副本,例如. temp_request = dict(shipping_request)
可以创建一个引用相同对象的新字典.但是,您可能希望import copy; copy.deepcopy
递归地复制字典中的每个对象.
Perhaps you want to make a shallow copy eg. temp_request = dict(shipping_request)
which makes a new dictionary with references to the same objects. However you may want a import copy; copy.deepcopy
to recursively copy every object inside the dictionary.
这篇关于有人可以解释这个错误吗?“运行时错误:字典大小在迭代过程中发生了变化"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!