基于多个键对字典列表进行排序的最佳方法是什么,并删除一些字典

时间:2013-04-17 09:23:15

标签: python list sorting optimization dictionary

基于多个键对词典列表进行排序并同时从输出中删除某些词典的最佳(时间)方法是什么?

我希望输出是所有词典的列表,其中"protected":0并按任意数量的其他键排序。

数据

[{"raffle_id":"81","created":"2013-01-07 19:47:57","instant":"1","protected":0,"expire":"never","ticket_price":"0.00050000",
"tickets_total":"10","tickets_sold":"1","my_tickets_count":"1"},
{"raffle_id":"83","created":"2013-01-07 19:49:20","instant":"0","protected":1,"expire":"4d 23h 59m","ticket_price":"0.01000000",
"tickets_total":"50","tickets_sold":"0","my_tickets_count":"0"}]

当前方法

raffle_list = [raffle for raffle in raffle_list if raffle("protected") == "0"]

sorted_raffles = sorted(raffles_list, key = operator.itemgetter("ticket_price", "tickets_sold", "my_tickets_count", "tickets_total"))

1 个答案:

答案 0 :(得分:1)

我所能建议的只是让raffle_list成为一个生成器,但根据可用的数据和内存,可能会/可能不会更快。例如。 list comps对于小数据集更快,但是生成器避免在内存中复制,这可以提高大型数据集的速度,因为sorted也可以复制:

(raffle for raffle in raffle_list if raffle("protected") == "0")