gpt4 book ai didi

Python 按两个值对列表进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:10 24 4
gpt4 key购买 nike

我正在尝试先按名称反向排序此列表。然后,在第一组结果(其中 flag = "ZAR")之后,我想按时间而不是反向对剩余元素进行排序:

import operator
list = [
{"flag":"ZAR", "time":"17:45"},
{"flag":"AUS", "time":"17:30"},
{"flag":"AUS", "time":"17:15"},
{"flag":"USA", "time":"17:00"},
{"flag":"GBP", "time":"16:55"},
{"flag":"ZAR", "time":"16:45"},
{"flag":"USA", "time":"16:35"},
{"flag":"GBP", "time":"16:25"},
{"flag":"ZAR", "time":"16:15"},
]

list.sort(key=operator.itemgetter("time"))
list.sort(key=operator.itemgetter("flag"),reverse=True)


print list

[{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]

如您所见,国旗排序正确,但其他元素仅按排序国家/地区内的时间排序。

我想要的是总是先有 ZAR,然后标志名称是什么并不重要,重要的是时间。所以它应该给出这个结果:

[{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]

这将如何完成?

最佳答案

将您的代码修改为:

import operator
data = [
{"flag":"ZAR", "time":"17:45"},
{"flag":"AUS", "time":"17:15"},
{"flag":"USA", "time":"17:00"},
{"flag":"GBP", "time":"16:55"},
{"flag":"ZAR", "time":"16:45"},
{"flag":"USA", "time":"16:35"},
{"flag":"GBP", "time":"16:25"},
{"flag":"ZAR", "time":"16:15"},
]

data.sort(key=operator.itemgetter("time"))
data.sort(key=lambda L: L['flag'] == 'ZAR', reverse=True)

# [{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]

关于Python 按两个值对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18571830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com