字典結構是:
info ={'car1':{'location':10,'speed':10},
'car2':{'location':5,'speed':20},
'car3':{'location':1,'speed':5},
'car4':{'location':50,'speed':30},
...}
現在,我想獲取所有汽車的速度資訊并對速度串列進行排序。然后,像這樣找到速度更快的汽車:
speed_list = [30,20,10,5]
fastest car: car4
dict.values() 可以獲取字典值, max(dict, dict.get) 可以獲取具有最大值的鍵,但在我的情況下它們不可用。
max(info, info.get)
'>' not supported between instances of 'dict' and 'dict'
max(info.values(), info.values.get)
'dict_values' object has no attribute 'get'
我應該怎么做才能得到速度最大的串列和車號?
uj5u.com熱心網友回復:
有一百萬種方法可以做到這一點,這里只有一種。
- 在構建(速度,汽車名稱)對的序列中使用 .items()。
- 對它進行排序(在這里,呼叫
sorted生成器運算式,但sort如果這條線被分成兩部分,并且 genexp 被串列理解替換,那么它會起作用) - 使用串列推導來獲取這些對的第一個元素 ->
speed_list。 - 獲取這些對中第一個的第二個元素(由于對串列按降序排序,第一個元素將是速度最快的汽車)->
fastest_car
info = {'car1':{'location':10,'speed':10},
'car2':{'location': 5,'speed':20},
'car3':{'location': 1,'speed': 5},
'car4':{'location':50,'speed':30}
}
cars = sorted(((v['speed'], k) for (k,v) in info.items()), reverse=True)
# or:
# cars = [(v['speed'], k) for (k,v) in info.items()]
# cars.sort(reverse=True)
speed_list = [s for (s,_) in cars]
_, fastest_car = cars[0]
print(speed_list) # [30, 20, 10, 5]
print(fastest_car) # 'car4'
uj5u.com熱心網友回復:
要獲得最快的汽車:
fastest_car = max(info, key=lambda car: info[car]['speed'])
獲取速度串列的另一種方法:
speed_list = sorted((d['speed'] for d in info.values()), reverse=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453477.html
上一篇:回傳兩個字典的差
