变量XXXX未定义

时间:2016-09-27 08:29:51

标签: python-2.7 dictionary key

我尝试在dict totals中找到最大值和相应的键,当我这样编码时,我可以得到正确答案:

highest_value = 0
highest_key = None
for a_country in totals.keys():
    if totals[a_country] > highest_value:
        highest_value = totals[a_country]
        highest_key = a_country  

当我使用其他方式时,出现错误" 变量highest_key未定义。"。

highest_value = 0
highest_key = None
for a_country in totals.keys():
        highest_value = totals[a_country] if totals[a_country] > highest_value else highest_value 
        highest_key = a_country if totals[a_country] > highest_value else highest_key 

我很困惑......我认为这两个代码是相同的......

1 个答案:

答案 0 :(得分:1)

将此视为总数:

totals={'20':'10','40':'20','60':'30','80':'40','100':'50','120':'60'}

<强>解释

对于你的第一个程序我得到了结果,

Value 60 Key 120

第二个代码的问题在于循环,在第一个程序中,您获得最高值并为其分配相应的密钥。但是第二次你已经给出了

highest_key = a_country if totals[a_country] > highest_value else highest_key

即。现在这里的最高价值是&#39; 60&#39;所以价值不会高于60,所以进入else并给出默认的none作为结果,

如果您将其更改为==,那么您将获得相应的密钥。

在这里,

totals={'20':'10','40':'20','60':'30','80':'40','100':'50','120':'60'}
highest_value = 0
highest_key = None
for a_country in totals.keys():
    print a_country
        highest_value = totals[a_country] if totals[a_country] > highest_value else highest_value 
        highest_key = a_country if totals[a_country] == highest_value else highest_key
print "Value",highest_value
print "Key",highest_key

结果是,

Value 60 Key 120