【发布时间】: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