3

我试图先按名称对这个列表进行反向排序。然后,在第一组结果(其中标志 =“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'}]

这将如何完成?

4

1 回答 1

5

将您的代码修改为:

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'}]
于 2013-09-02T11:20:46.473 回答