繁体   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