You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中忽略空格与大小写排序字典键列表的优化方法咨询

优化字典键列表的排序方案

我有一个由字典键组成的列表需要排序,原列表如下:

listToBeSorted = ["Right  Coronary Artery 2", "Right Coronary Artery 1", "RIght Coronary Artery 3"]

预期排序结果:

["Right Coronary Artery 1", "Right  Coronary Artery 2", "RIght Coronary Artery 3"]

排序要求:忽略元素中的连续空格,同时忽略大小写差异(比如最后一个元素里的大写"I"),且不能修改原元素(后续要用来访问字典)。

尝试过的三种排序方式

  • 基础排序
sortedList = sorted(listToBeSorted)

得到结果:

['RIght Coronary Artery 3',
 'Right  Coronary Artery 2',
 'Right Coronary Artery 1']
  • 忽略大小写排序
sortedList = sorted(listToBeSorted, key=str.casefold)

得到结果:

['Right  Coronary Artery 2',
 'Right Coronary Artery 1',
 'RIght Coronary Artery 3']
  • 去除空格后排序
sortedList = sorted(listToBeSorted, key=lambda x: ''.join(x.split()))

得到结果:

['RIght Coronary Artery 3',
 'Right Coronary Artery 1',
 'Right  Coronary Artery 2']

原实现方案(繁琐低效)

我之前通过构建元组列表添加排序辅助字段的方式实现了需求,但代码冗余且效率较低:

sortedListWithTwin = []
    
# 添加去除空格的大写版本作为排序依据
for item in listToBeSorted:
  sortString = (item.upper()).replace(" ","")
  sortedListWithTwin.append((item, sortString))
       
# 按辅助字段排序
sortedListWithTwin.sort(key = lambda x: x[1])
    
# 提取原元素
sortedList = []
for item in sortedListWithTwin:
  sortedList.append(item[0])

更优解决方案

无需额外构建临时列表,直接在sorted()的key参数中生成统一的排序依据即可。核心是对每个元素生成去除所有空格+大小写统一的字符串作为排序键,既满足排序规则,又不会修改原元素。

优化后的代码(两种写法效果一致):

写法一:用replace去除空格

sortedList = sorted(
    listToBeSorted,
    key=lambda x: x.upper().replace(" ", "")
)

写法二:用split+join去除空格(适合复杂空格场景)

sortedList = sorted(
    listToBeSorted,
    key=lambda x: ''.join(x.upper().split())
)

这两种写法都能直接得到预期的排序结果,代码简洁高效,不需要额外循环和临时变量。

内容的提问来源于stack exchange,提问作者Spinlock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:35:48