我有一本字典,其中包含一些賽車手,如下所示:
dict = {('Richard','Ringer'):['Germany',(2,11,27)], \
('Eliud','Kipchoge'):['Kenya',(2,8,38)], \
('Yavuz','Agrali'):['Turkey',(2,15,5)]
}
#('Richard','Ringer')=name
#'Germany'=country
#(2,11,27)=complation time of the race; hours, minutes and seconds.
我想把以秒為單位計算的鍵值(即名字和姓氏)和時間按升序排列:
for i in dict:
name=i[0]
surname=i[1]
liselement=name " " surname
country=dict[i][0]
hours=dict[i][1][0]
minutes=dict[i][1][1]
seconds=dict[i][1][2]
inseconds=(hours*60*60) minutes*60 seconds
dictmedal[liselement,country]=inseconds
sorted_dictmedal = sorted(dictmedal.items(),key=lambda kv:kv[0])
for nth,key in zip(('Gold Medal:','Silver Medal:','Bronze Medal:'),dictmedal):
print(nth,*key)
for nth,key in zip(('Gold Medal:','Silver Medal:','Bronze Medal:'),sorted_dictmedal):
print(nth,*key)
輸出:
Gold Medal: Richard Ringer Germany
Silver Medal: Eliud Kipchoge Kenya
Bronze Medal: Yavuz Agrali Turkey
Gold Medal: ('Eliud Kipchoge', 'Kenya') 7718
Silver Medal: ('Richard Ringer', 'Germany') 7887
Bronze Medal: ('Yavuz Agrali', 'Turkey') 8105
有沒有辦法讓 sorted_dictmedal 看起來像 dictmedal 輸出?另外,有沒有辦法在名字和城市之間加上逗號?
Gold Medal: Richard Ringer, Germany
uj5u.com熱心網友回復:
也許你可以使用元組解包:
racers = {
('Richard', 'Ringer'): ['Germany', (2, 11, 27)],
('Eliud', 'Kipchoge'): ['Kenya', (2, 8, 38)],
('Yavuz', 'Agrali'): ['Turkey', (2, 15, 5)],
}
medals = {}
for (first_name, last_name), [country, (hours, minutes, seconds)] in racers.items():
time_in_seconds = hours * 60 * 60 minutes * 60 seconds
racer_key = f'{first_name} {last_name}, {country}'
medals[racer_key] = time_in_seconds
print('Unsorted:')
for medal, (racer_key, time) in zip(('Gold Medal:', 'Silver Medal:', 'Bronze Medal:'), medals.items()):
print(medal, racer_key)
print('\nSorted:')
for medal, (racer_key, time) in zip(('Gold Medal:', 'Silver Medal:', 'Bronze Medal:'), sorted(medals.items(), key=lambda m: m[1])):
print(medal, racer_key)
輸出:
Unsorted:
Gold Medal: Richard Ringer, Germany
Silver Medal: Eliud Kipchoge, Kenya
Bronze Medal: Yavuz Agrali, Turkey
Sorted:
Gold Medal: Eliud Kipchoge, Kenya
Silver Medal: Richard Ringer, Germany
Bronze Medal: Yavuz Agrali, Turkey
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381472.html
上一篇:如何使用Python中的比較器按頻率對整數串列進行排序?
下一篇:使用遞回進行選擇排序
