Python排序异常:带括号与无括号项排序顺序错误排查
待办项排序逻辑异常问题排查
原始数据结构
[(1, '(A) Begin plans for world domination'), (2, 'Listen to Symphony for the New World'), (3, '(A) Change world'), (4, '(D) Listen to Symphony for the New World'), (5, '(C) Hello, World!'), (4, 'Improve Python todo project'), (6, 'Begin plans for world domination'), (7, '(A) Improve Python todo project')]
需求与问题
需求:先按括号内的内容(若存在括号)排序,再按数字排序。目前关键词过滤功能正常,但排序逻辑出错。
当前排序代码
filtered_items = [ (i+1, line.strip()) for i, line in enumerate(items) if not args.filter_string or args.filter_string.lower() in line.lower() ] sorted_items = sorted(filtered_items, key=lambda item: ( not item[1].startswith('('), item[1][:3], item[0], ))
当前错误排序结果
1 (A) Begin plans for world domination 3 (A) Change world 7 (A) Improve Python todo project 5 (C) Hello, World!'), (4, 'Improve Python todo project 4 (D) Listen to Symphony for the New World 6 Begin plans for world domination 2 Listen to Symphony for the New World
问题:最后两项(数字6和2)的顺序错误,不符合按数字排序的要求。
原因分析
问题出在排序键的第二部分item[1][:3]:
- 对于带括号的项,这个字段取的是
(A)、(C)这类前缀,能正常按括号内字母排序; - 但对于不带括号的项,它取的是文本的前三个字符(比如项6的
Beg、项2的Lis)。因为Beg的字典序比Lis小,所以项6会被排在项2前面,直接覆盖了第三优先级的数字排序逻辑,导致最终顺序不符合预期。
你的需求是无括号项之间按数字排序,所以这部分不能用文本前缀来排序,得把无括号项归为同一组,组内只按数字排序。
修正后的排序代码
sorted_items = sorted(filtered_items, key=lambda item: ( # 第一优先级:带括号的项排前面,无括号的排后面 not item[1].startswith('('), # 第二优先级:带括号的取括号内的字母,无括号的用空字符串统一归组 item[1][1] if item[1].startswith('(') else '', # 第三优先级:按数字排序 item[0] ))
修正后,无括号的项会被分到同一组(第二键为空字符串),组内直接按数字排序,项2会排在项6前面,符合需求。
内容的提问来源于stack exchange,提问作者Alex Hoggett
相关产品推荐
相关产品推荐

