利用队列来实现,可以满足任意多个字段,任意升序和降序的排序的场景,比如“按照a字段升序,b字段降序,c字段升序”
[{"balance_time": "desc"}, {"bk_id": "asc"}, {"trans_id": "desc"}]
asc升序
desc降序
unsorted_list={'1':{"balance_time":12344,"bk_id":45646,"trans_id":78940},'2':{"balance_time":12344,"bk_id":45647,"trans_id":78941},'3':{"balance_time":12344,"bk_id":45648,"trans_id":78942},'4':{"balance_time":12345,"bk_id":45642,"trans_id":78943},'5':{"balance_time":12345,"bk_id":45641,"trans_id":78944},'6':{"balance_time":12345,"bk_id":45640,"trans_id":78944},'7':{"balance_time":12346,"bk_id":"45649","trans_id":78944},'8':{"balance_time":12346,"bk_id":45648,"trans_id":78941},'9':{"balance_time":12346,"bk_id":45647,"trans_id":78941}}
具体实现:
def comprex_sort_index_list(self,sort_feild_array,unsorted_list):
sort_item_queue= Queue.Queue()
sort_item_queue.put(unsorted_list)
for sort in sort_feild_array:
sort_item_queue_temp = Queue.Queue()
sort_feild=sort.keys()[0]
is_reverse=True if sort[sort_feild]=="desc" else False
while not sort_item_queue.empty():
queue_item=sort_item_queue.get()
if isinstance(queue_item,dict):
queue_item = tuple(queue_item.items())
result_sort=sorted(queue_item,key=lambda x:x[1][sort_feild],reverse=is_reverse)
sort_feild_value_dictinct=sorted(list(set(map(lambda x:x[1][sort_feild],result_sort))),reverse=is_reverse)
for feild_value in sort_feild_value_dictinct:
sort_item_queue_temp.put(filter(lambda x:x[1][sort_feild]==feild_value,result_sort))
sort_item_queue=sort_item_queue_temp
sorted_list=list()
while not sort_item_queue.empty():
sorted_list=sorted_list+sort_item_queue.get()
return sorted_list