2016-09-27 66 views
0

我試圖找到在字典totals最大的價值和相應的鍵,當我像這樣的代碼,我可以得到正確的答案:變量XXXX是不確定的

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 

我很困惑。我認爲這兩個代碼是相同的....

+0

你能給'totals'的例子嗎? –

回答

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

即這裏最高值現在是「60」。所以不會比60更大的價值,所以進入其他,並給出默認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

+0

明白了,謝謝! –