加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python 3按值排序字典列表,其中值以字符串开头

发布时间:2020-12-20 11:56:41 所属栏目:Python 来源:网络整理
导读:试图弄清楚如何按值对字典列表进行排序,其中值以“自定义地图”列表中的字符串开头.例如,这里是要排序的数据: 'buckets': [ { 'doc_count': 23,'key': 'Major League Stuff' },{ 'doc_count': 23,'key': 'Football Stuff' },'key': 'Football Stuff Footbal
试图弄清楚如何按值对字典列表进行排序,其中值以“自定义地图”列表中的字符串开头.例如,这里是要排序的数据:

'buckets': [
    {
        'doc_count': 23,'key': 'Major League Stuff'
    },{
        'doc_count': 23,'key': 'Football Stuff'
    },'key': 'Football Stuff > Footballs'
    },'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'
    },'key': 'Jewelry > Rings'
    },{
        'doc_count': 2,'key': 'All Gifts'
    },'key': 'Gifts for Her'
    },'key': 'Gifts for Her > Jewelry'
    },'key': 'Football Stuff > Footballs > Tykes'
    },{
        'doc_count': 1,'key': 'Brand new items'
    },'key': 'Jewelry > Rings and Bands'
    }
    {
        'doc_count': 1,'key': 'Football Stuff > Footballs > High School'
    },'key': 'Football Stuff > Pads'
    }
]

我想根据这个列表对它进行排序:

sort_map = ['Football Stuff','Jewelry','Gifts for Her','Brand new items','Major League Stuff','All Gifts']

我有点想“startwith”可以工作,但我不确定如何

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

任何帮助赞赏!

旁注 – SO要求我编辑解释为什么这篇文章与其他“按价值排序”字样不同.在发布此内容之前,我确实查看了很多这样的内容,并且没有涉及匹配字符串部分的内容.所以我相信这不是重复的.

解决方法

我会利用你可以根据“>”拆分并获取第一个字段的索引这一事实

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读