在赋值错误

时间:2017-12-04 21:52:08

标签: python dictionary

我需要编写一个代码,该代码应该将字典中的项目放入列表中,并在键或值之后对它们进行排序。这是我提出的代码:

import copy
dict_ip_attempts = {"180.237.210.112": 9, "180.237.210.54": 5,
                     "180.237.210.13": 2, "180.237.210.30": 5}

d=copy.deepcopy(dict_ip_attempts)
ip_adress=[]
for key in dict_ip_attempts:
    var=key.split(".")
    ip_adress.append(int("".join(var)))

ip_adress.sort()

def sortip_adress():
    output=[0]*(len(ip_adress))
    for key in dict_ip_attempts:
        var=key.split(".")
        for i in range(len(ip_adress)):
            if int("".join(var)) == ip_adress[i]:
                output[i]=((key, dict_ip_attempts[key]))
    return output

def sortattempts():
    output=[]
    for key in dict_ip_attempts:
        if dict_ip_attempts[key]==min(dict_ip_attempts.values()):
            output.append((key, dict_ip_attempts[key]))
            dict_ip_attempts.pop(key)
    dict_ip_attempts=copy.deepcoy(d)
    return output

print("The dictionary sorted after the ip_adresses is:", sortip_adress())
print("The dictionary sorted after the attempts is:", sortattempts())

函数sortip_adress()工作正常,但sortattempts()函数不行。当python到达第30行时,它会打印:UnboundLocalError:local variable' dict_ip_attempts'在分配前引用

第30行是这一个:

for key in dict_ip_attempts:

我不明白为什么会出现这个错误,因为我在第2行定义了dict_ip_attempts。有人可以解释一下吗?

2 个答案:

答案 0 :(得分:1)

global dict_ip_attempts函数的开头添加sortattempts

编辑: 基本上,你尝试做的是以更加pythonic的方式描述here

答案 1 :(得分:0)

将全局dict_ip_attempts添加为两个函数声明下的一行,因为它是一个全局变量。同样从字典循环中的for键中的字典中弹出值是一个坏主意(正如Wondercricket所提到的)。它应该没有必要,但如果您需要清空字典,只需在完成循环dict_ip_attempts = {}

之后执行此操作