Python3按值对字典列表进行排序,其中值以字符串开头

2024-10-01 13:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

试图找出如何按值对字典列表排序,其中值以“自定义映射”列表中的字符串开头。例如,以下是要排序的数据:

'buckets': [
    {
        'doc_count': 23,
        'key': 'Major League Stuff'
    },
    {
        'doc_count': 23,
        'key': 'Football Stuff'
    },
    {
        'doc_count': 23,
        'key': 'Football Stuff > Footballs'
    },
    {
        'doc_count': 23,
        'key': 'Football Stuff > Footballs > Pro'
    },
    {
        'doc_count': 22,
        'key': 'Football Stuff > Footballs > College'
    },
    {
        'doc_count': 20,
        'key': 'Football Stuff > Football Stuff Collections > Neat Stuff'
    },
    {
        'doc_count': 19,
        'key': 'Football Stuff > Helmets'
    },
    {
        'doc_count': 4,
        'key': 'Jewelry'
    },
    {
        'doc_count': 4,
        'key': 'Jewelry > Rings'
    },
    {
        'doc_count': 2,
        'key': 'All Gifts'
    },
    {
        'doc_count': 2,
        'key': 'Gifts for Her'
    },
    {
        'doc_count': 2,
        'key': 'Gifts for Her > Jewelry'
    },
    {
        'doc_count': 2,
        'key': 'Football Stuff > Footballs > Tykes'
    },
    {
        'doc_count': 1,
        'key': 'Brand new items'
    },
    {
        'doc_count': 1,
        'key': 'Jewelry > Rings and Bands'
    }
    {
        'doc_count': 1,
        'key': 'Football Stuff > Footballs > High School'
    },
    {
        'doc_count': 1,
        'key': 'Football Stuff > Pads'
    }
]

我想根据这个列表来分类:

^{pr2}$

我有点想“startswith”能起作用,但我不知道怎么做

buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].startswith[?]))

感谢任何帮助!在

旁注-所以请我编辑,解释为什么这篇文章不同于其他“按值排序”的帖子。在发布这篇文章之前,我确实尽可能多地查看了这些内容,并且没有涉及字符串匹配部分的内容。所以我相信这不是复制品。在


Tags: key字符串列表fordoc排序countstuff
2条回答

我认为最好是创建一个单独的函数,而不是lambda,因为这样可以使代码更易于理解。在

def get_index(x):
    for i, e in enumerate(sort_map):
        if x['key'].startswith(e):
            return i

buckets = sorted(buckets, key=get_index)

我将利用这样一个事实:您可以根据" > "进行拆分,并获取第一个字段的索引

buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].split(" > ")[0]))

为了提供第二个alpha条件,您可以返回一个元组,其中完整的字符串作为第二项,以便在相同索引的情况下按字母顺序排序:

^{pr2}$

相关问题 更多 >