【问题标题】:After sorting dictionary, the output is not the same?字典排序后,输出不一样?
【发布时间】: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


【解决方案1】:

也许你可以使用元组解包:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 2021-09-04
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多