2017-06-22 53 views
-1

這是我的代碼示例:如何根據值顯示索引?

budi = {"Name" : "Budi", "Gender" : "Male", "Age" : 18} 
ahmad = {"Name" : "Ahmad", "Gender" : "Male", "Age" : 7} 
ika = {"Name" : "Ika", "Gender" : "Female", "Age" : 18} 

marged = [budi, ahmad, ika] 

我想要的結果是這樣,例如基礎上,18歲的:

The oldest participants are: Budi and Ika 
+0

你有什麼試過嗎? –

+2

你可以用Python玩更多... – coderredoc

回答

-1

這是根據什麼你在問代碼題。請通過這個非常簡單的實現。

from operator import itemgetter 

budi = {"Name" : "Budi", "Gender" : "Male", "Age" : 1} 
ahmad = {"Name" : "Ahmad", "Gender" : "Male", "Age" : 7} 
ika = {"Name" : "Ika", "Gender" : "Female", "Age" : 18} 

marged = [budi, ahmad, ika] 

newlist = sorted(marged, key=itemgetter('Age'), reverse=True) 

maxAge = newlist[0]["Age"] 
finalList = [newlist[0]["Name"]] 
for person in newlist[1:]: 
    if person["Age"] == maxAge: 
     finalList.append(person["Name"]) 

if len(finalList) == 1: 
    print "The oldest participant is: " + finalList[0] 
else: 
    print "The oldest participants are: ", 
    for name in finalList: 
     print name+" ",