首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过定义排序顺序,按子字典键对python字典键进行排序

问通过定义排序顺序,按子字典键对python字典键进行排序
EN

Stack Overflow用户
提问于 2018-03-06 07:40:34
回答 3查看 917关注 0票数 7

我的问题是another question的一个扩展,其中OP有一个字典,如下所示,并希望根据子字典键对主键进行排序

代码语言:javascript
复制
myDict = {
    'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
    'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
    'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
    'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'},
    'ABC12346': {'serial_num': 'ABC12346', 'site_location': 'Europe'}
}

建议的解决方案(引用如下)可以完美地工作。

代码语言:javascript
复制
dicts = myDict.items()
dicts.sort(key=lambda (k,d): (d['site_location'], d['serial_num'],))

然而,这个解决方案对所有人都是按升序排序的(降序排序很简单)。我想知道是否有可能定义混合的排序顺序,比如升序的serial_num和降序的site_location?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-03-06 08:03:43

这是一种可能的解决方案,因为列表排序是stable。我稍微更改了数据,以证明它是有效的。

此方法在Python documentation中也有规定。

代码语言:javascript
复制
myDict = {
    'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
    'ABC12346': {'serial_num': 'ABC12345', 'site_location': 'Europe'},
    'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
    'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
    'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'}
}

result = sorted(myDict.items(), key=lambda x: x[1]['site_location'], reverse=True)
result = sorted(result, key=lambda x: x[1]['serial_num'])

# [('ABC12345', {'serial_num': 'ABC12345', 'site_location': 'South America'}),
#  ('ABC12346', {'serial_num': 'ABC12345', 'site_location': 'Europe'}),
#  ('SER12345', {'serial_num': 'SER12345', 'site_location': 'North America'}),
#  ('SER12346', {'serial_num': 'SER12346', 'site_location': 'North America'}),
#  ('SER12347', {'serial_num': 'SER12347', 'site_location': 'South America'})]
票数 2
EN

Stack Overflow用户

发布于 2018-03-06 08:53:14

如果您确实需要一个自定义排序顺序,那么您可以使用排序逻辑编写一个自定义对象,该对象将充当底层实际对象的包装器。

代码语言:javascript
复制
from functools import total_ordering
# total_ordering keeps you from having to write each of
# __gt__, __ge__, __lt__, __le__. It requires __eq__ and one of the
# other comparison functions to be defined and the rest are assumed
# in terms of each other.  (__ge__ = __gt__ or __eq__, __gt__ = not __le__), etc.

@total_ordering
class CustomSorter(object):
    def __init__(self, data):
        self.data = data

    # the properties here are solely to make the code a little more readable
    # in the rich comparators below. You can ignore them if you like.
    @property
    def serial_number(self):
        return self.data[1]["serial_number"]
    @property
    def site_location(self):
        return self.data[1]["site_location"]

    def __eq__(self, other):
        if not isinstance(other, CustomSorter):
            raise NotImplementedError("CustomSorters can only sort with themselves")
        return self.data[1] == other.data[1]

    def __lt__(self, other):
        if not isinstance(other, CustomSorter):
            raise NotImplementedError("CustomSorters can only sort with themselves")
        if self.site_location == other.site_location:
            return self.site_number < other.site_number
        else:
            return not (self.site_location < other.site_location)

然后使用传统的装饰-排序-取消装饰步骤。

代码语言:javascript
复制
myDict = {
    'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'},
    'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'},
    'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'},
    'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'},
    'ABC12346': {'serial_num': 'ABC12346', 'site_location': 'Europe'}
}
sorters = [CustomSorter(tup) for tup in myDict.items()]
sorters.sort()
result = [sorter.data for sorter in sorters]

如果您实现一个函数来为您排序,这可能是最好的。

代码语言:javascript
复制
def sort_on(sorter, unsorted):
    """sort_on expects @sorter@ to be a class with rich comparison operations
    that is a decorative wrapper around some data to be sorted. Additionally,
    @sorter.data@ should refer to the underlying data structure.
    """

    decorated = [sorter(unsort) for unsort in unsorted]
    decosorted = decorated.sort()
    sorted = [decosort.data for decosort in decosorted]
    return sorted

result = sort_on(CustomSorter, myDict.items())
票数 2
EN

Stack Overflow用户

发布于 2018-03-06 09:16:27

我认为您使用元组进行单一排序的方法是最具Pythonic风格的,所以我坚持使用这种方法。如果值都是数值,您可以很容易地对任何元组值求反,以获得键的该部分的逆序,但这里的问题是您想要求反一个字符串,对吧?所以让我们来解决这个问题:

代码语言:javascript
复制
def str_to_neg_ords(s):
    return tuple(-ord(c) for c in s)

现在,您可以将此函数用作键的一部分,以执行嵌套词典排序:

代码语言:javascript
复制
sorted(myDict.values(),
       key=lambda d: (str_to_neg_ords(d['site_location']), d['serial_num']))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49121246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档