有人可以解释这个错误 - “运行时错误:字典大小在迭代期间发生了变化”?

时间:2013-05-24 08:00:09

标签: python python-2.x itertools

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   

这会出现以下错误 - “运行时错误:迭代期间字典大小已更改”

我做错了什么?我怎么能以不同的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

这与itertools.combinations无关,您试图更改迭代的数据结构,这是不允许的:

Runtime error: dictionary size changed during iteration

您尝试在迭代时从字典中添加或删除键。一种解决方法是迭代for key in list(dictionary),它会生成字典键的副本列表,因此您仍然可以修改基础字典,但是您可能还想重新考虑一般方法。

导致错误的行是:

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以递归方式复制字典中的每个对象。