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

如何按两级自定义字符串匹配规则对Python列表重排序?

Python列表自定义多级排序实现方案

需求回顾

给定以下Python列表:

['T20221019A_E3.B Allele Freq',
 'T20221019A_E3.Log R Ratio',
 'T20221019A_E3.Gtype',
 'Father_FM.B Allele Freq',
 'Father_FM.Log R Ratio',
 'Father_FM.Gtype',
 'Mother_FS.B Allele Freq',
 'Mother_FS.Log R Ratio',
 'Mother_FS.Gtype']

需要实现:

  1. 一级排序:按.左侧内容,遵循Mother_FS → Father_FM → T20221019A_E3的顺序
  2. 二级排序:按.右侧内容,遵循Gtype → B Allele Freq → Log R Ratio的顺序

简洁实现方案

利用Python内置的sorted()函数,结合自定义排序键(通过优先级映射字典实现),是最简洁高效的方式:

original_list = [
    'T20221019A_E3.B Allele Freq',
    'T20221019A_E3.Log R Ratio',
    'T20221019A_E3.Gtype',
    'Father_FM.B Allele Freq',
    'Father_FM.Log R Ratio',
    'Father_FM.Gtype',
    'Mother_FS.B Allele Freq',
    'Mother_FS.Log R Ratio',
    'Mother_FS.Gtype'
]

# 定义两级排序的优先级映射(数字越小优先级越高)
primary_priority = {'Mother_FS': 0, 'Father_FM': 1, 'T20221019A_E3': 2}
secondary_priority = {'Gtype': 0, 'B Allele Freq': 1, 'Log R Ratio': 2}

# 执行排序:先按一级优先级,再按二级优先级
sorted_result = sorted(original_list, key=lambda item: (
    primary_priority[item.split('.')[0]],
    secondary_priority[item.split('.')[1]]
))

print(sorted_result)

代码解释

  1. 优先级映射字典:将需要排序的字符串映射为数字,数字越小代表排序位置越靠前,这样sorted()会自动按数字升序排列,完全匹配需求的顺序。
  2. 自定义排序键:通过lambda表达式拆分每个元素的.左右部分,分别获取对应的优先级数字,形成元组作为排序依据——元组比较会先对比第一个元素(一级排序),第一个元素相同时再对比第二个元素(二级排序)。
  3. 输出结果:运行后会得到符合预期的排序列表:
['Mother_FS.Gtype',
 'Mother_FS.B Allele Freq',
 'Mother_FS.Log R Ratio',
 'Father_FM.Gtype',
 'Father_FM.B Allele Freq',
 'Father_FM.Log R Ratio',
 'T20221019A_E3.Gtype',
 'T20221019A_E3.B Allele Freq',
 'T20221019A_E3.Log R Ratio']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:05:13