具有赋值的字典在赋值之前引用

2024-09-30 06:15:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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_address()工作正常,但sortattempts()函数不工作。当python到达第30行时,它将输出:UnboundLocalError:赋值前引用的局部变量“dict_ip_attempts”

第30行是这个:

^{pr2}$

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


Tags: key代码inipforoutputvardict
2条回答

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

sortattempts函数的开头添加global dict_ip_attempts。在

编辑: 基本上,你要做的是用一种更具Python式的方式来描述here。在

相关问题 更多 >

    热门问题