我有一個像這樣的 touples 的 python 串列:
touple = [('Northwest Airlines', 93),
('Northwest Airlines', 81),
('Southwest Airlines', 79),
('NorthWestern', 77),
('NorthWestern', 69),
('Southwest Airlines', 69)]
其中一些專案是重復的。我只想保留具有最大值的唯一 Touples 作為第二項。
我想要實作的輸出是這樣的:
processed_touple = [('Northwest Airlines', 93),
('Southwest Airlines', 79),
('NorthWestern', 77)]
實作這一目標的最簡單方法是什么?
uj5u.com熱心網友回復:
dic = {}
for item in touple:
name, score = item
if name not in dic:
dic[name] = score
else:
if score > dic[name]:
dic[name] = score
print(list(dic.items()))
輸出:
[('Northwest Airlines', 93), ('Southwest Airlines', 79), ('NorthWestern', 77)]
uj5u.com熱心網友回復:
tmp = dict((y, x) for x, y in touple)
my_dict = dict()
for val, key in tmp.items():
if key not in my_dict.keys():
my_dict[key] = val
else:
if my_dict[key] < val:
my_dict[key] = val
輸出:my_dict
{'Northwest Airlines': 93, 'Southwest Airlines': 79, 'NorthWestern': 77}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/529491.html
標籤:Python数组排序
