【问题标题】:dictionary with assigned value raises referenced before assignment error赋值错误之前引用的具有赋值的字典引发了引用
【发布时间】:2017-12-04 21:52:08
【问题描述】:

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

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' referenced before assignment

第 30 行是这一行:

for key in dict_ip_attempts:

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

【问题讨论】:

  • global dict_ip_attempts 添加为两个函数声明下方的一行,因为它是一个全局变量
  • 另外,在遍历dict_ip_attempts 时不要执行dict_ip_attempts.pop(key)。这将导致错误和意外结果
  • 请发布完整的 Traceback。

标签: python dictionary


【解决方案1】:

sortattempts函数的开头添加global dict_ip_attempts

编辑: 基本上,您尝试做的事情会以更加 Python 的方式描述 here

【讨论】:

  • RuntimeError: 迭代期间字典大小改变
  • @Christian 查看我对您的回答的评论
【解决方案2】:

将 global dict_ip_attempts 添加为两个函数声明下方的一行,因为它是一个全局变量。在字典循环中的 for 键中从字典中弹出一个值也是一个坏主意(如 Wondercricket 所述)。这应该不是必需的,但是如果您需要清空字典,只需在循环完成后使用 dict_ip_attempts = {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    相关资源
    最近更新 更多