【发布时间】:2022-01-17 09:30:46
【问题描述】:
我有一本包含一些赛车手的字典,如下所示:
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
【问题讨论】:
-
你不需要反斜杠在字典中间继续。
-
sorted_dictmedal的赋值不需要在循环内。
标签: python sorting dictionary