簡體   English   中英

Python:字典列表的復雜排序

[英]Python: complex sort of list of dictionaries

我有一個字典列表,其元素必須根據相當復雜的標准進行排序。 請考慮以下典型元素:

{
    'key1': True,                 # always boolean
    'key2': False,                # always boolean
    'key3': 23,                   # always int
    'key4': 1613.34,              # always float
    'key5': 'Some string',        # always str
    'key6': 'Some other string',  # always str
}

假設所需的排序順序是: key1 ASC, key2 DESC, key3 ASC, key4 DESC, key5 ASC, key6 DESC

我知道我可以做這樣的事情:

my_sorted_list = sorted(my_list, key=lambda my_dict: (
    my_dict['key1'],
    -my_dict['key2'],
    my_dict['key3'],
    -my_dict['key4'],
    my_dict['key5'],
    tuple(-ord(c) for c in my_dict['key6'])     # is that really the way of doing it? :-| 
))

但對我來說,最后一種表達方式似乎非常丑陋和駭人聽聞(也許效率低下)。 是否有執行相同分類的最簡潔方法?

根據此操作的時間緊迫程度,最好按順序執行各種排序。 因此,給定一個帶有(field,order)元組的sort_control列表,您可以多次排序以實現正確的排序:

from operator import itemgetter


def sort_list(in_list, sort_control):
    out_list = in_list.copy()
    for field, fwd in reversed(sort_control):
         out_list.sort(key=itemgetter(field), reverse = not fwd)
    return out_list

my_sorted_list = sort_list(my_list, [('key1',True), ('key2',False), ('key3',True), ('key4',False), ('key5',True), ('key6',False)])

一種方法是實現比較 function。 與其他響應相比,它的好處是只運行一次對排序/排序的調用。 不知道是快了還是慢了。

from functools import cmp_to_key

def keyorder(sort_control):
    def compare(a, b): # Custom comparison function to return
        for field, fwd in sort_control:
            comparison = (a[field] > b[field]) - (a[field] < b[field]) # 1 if a>b, 0 if a==b, -1 if a < b
            if comparison:
                if not fwd:
                    comparison = -comparison
                break
        return comparison
    return cmp_to_key(compare) # Create key from comparison function

    my_sorted_list = sorted(my_list, key=keyorder([('key1',True), ('key2',False), ('key3',True), ('key4',False), ('key5',True), ('key6',False)]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM